objstr.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. * Copyright (c) 2014-2018 Paul Sokolovsky
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include <string.h>
  28. #include <assert.h>
  29. #include "py/unicode.h"
  30. #include "py/objstr.h"
  31. #include "py/objlist.h"
  32. #include "py/runtime.h"
  33. #include "py/stackctrl.h"
  34. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  35. STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
  36. #endif
  37. STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
  38. STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
  39. /******************************************************************************/
  40. /* str */
  41. void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
  42. // this escapes characters, but it will be very slow to print (calling print many times)
  43. bool has_single_quote = false;
  44. bool has_double_quote = false;
  45. for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
  46. if (*s == '\'') {
  47. has_single_quote = true;
  48. } else if (*s == '"') {
  49. has_double_quote = true;
  50. }
  51. }
  52. int quote_char = '\'';
  53. if (has_single_quote && !has_double_quote) {
  54. quote_char = '"';
  55. }
  56. mp_printf(print, "%c", quote_char);
  57. for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
  58. if (*s == quote_char) {
  59. mp_printf(print, "\\%c", quote_char);
  60. } else if (*s == '\\') {
  61. mp_print_str(print, "\\\\");
  62. } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
  63. // In strings, anything which is not ascii control character
  64. // is printed as is, this includes characters in range 0x80-0xff
  65. // (which can be non-Latin letters, etc.)
  66. mp_printf(print, "%c", *s);
  67. } else if (*s == '\n') {
  68. mp_print_str(print, "\\n");
  69. } else if (*s == '\r') {
  70. mp_print_str(print, "\\r");
  71. } else if (*s == '\t') {
  72. mp_print_str(print, "\\t");
  73. } else {
  74. mp_printf(print, "\\x%02x", *s);
  75. }
  76. }
  77. mp_printf(print, "%c", quote_char);
  78. }
  79. #if MICROPY_PY_UJSON
  80. void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
  81. // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
  82. // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
  83. mp_print_str(print, "\"");
  84. for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
  85. if (*s == '"' || *s == '\\') {
  86. mp_printf(print, "\\%c", *s);
  87. } else if (*s >= 32) {
  88. // this will handle normal and utf-8 encoded chars
  89. mp_printf(print, "%c", *s);
  90. } else if (*s == '\n') {
  91. mp_print_str(print, "\\n");
  92. } else if (*s == '\r') {
  93. mp_print_str(print, "\\r");
  94. } else if (*s == '\t') {
  95. mp_print_str(print, "\\t");
  96. } else {
  97. // this will handle control chars
  98. mp_printf(print, "\\u%04x", *s);
  99. }
  100. }
  101. mp_print_str(print, "\"");
  102. }
  103. #endif
  104. STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  105. GET_STR_DATA_LEN(self_in, str_data, str_len);
  106. #if MICROPY_PY_UJSON
  107. if (kind == PRINT_JSON) {
  108. mp_str_print_json(print, str_data, str_len);
  109. return;
  110. }
  111. #endif
  112. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  113. bool is_bytes = mp_obj_is_type(self_in, &mp_type_bytes);
  114. #else
  115. bool is_bytes = true;
  116. #endif
  117. if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
  118. mp_printf(print, "%.*s", str_len, str_data);
  119. } else {
  120. if (is_bytes) {
  121. mp_print_str(print, "b");
  122. }
  123. mp_str_print_quoted(print, str_data, str_len, is_bytes);
  124. }
  125. }
  126. mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  127. #if MICROPY_CPYTHON_COMPAT
  128. if (n_kw != 0) {
  129. mp_arg_error_unimpl_kw();
  130. }
  131. #endif
  132. mp_arg_check_num(n_args, n_kw, 0, 3, false);
  133. switch (n_args) {
  134. case 0:
  135. return MP_OBJ_NEW_QSTR(MP_QSTR_);
  136. case 1: {
  137. vstr_t vstr;
  138. mp_print_t print;
  139. vstr_init_print(&vstr, 16, &print);
  140. mp_obj_print_helper(&print, args[0], PRINT_STR);
  141. return mp_obj_new_str_from_vstr(type, &vstr);
  142. }
  143. default: // 2 or 3 args
  144. // TODO: validate 2nd/3rd args
  145. if (mp_obj_is_type(args[0], &mp_type_bytes)) {
  146. GET_STR_DATA_LEN(args[0], str_data, str_len);
  147. GET_STR_HASH(args[0], str_hash);
  148. if (str_hash == 0) {
  149. str_hash = qstr_compute_hash(str_data, str_len);
  150. }
  151. #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  152. if (!utf8_check(str_data, str_len)) {
  153. mp_raise_msg(&mp_type_UnicodeError, NULL);
  154. }
  155. #endif
  156. // Check if a qstr with this data already exists
  157. qstr q = qstr_find_strn((const char*)str_data, str_len);
  158. if (q != MP_QSTR_NULL) {
  159. return MP_OBJ_NEW_QSTR(q);
  160. }
  161. mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len));
  162. o->data = str_data;
  163. o->hash = str_hash;
  164. return MP_OBJ_FROM_PTR(o);
  165. } else {
  166. mp_buffer_info_t bufinfo;
  167. mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
  168. #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  169. if (!utf8_check(bufinfo.buf, bufinfo.len)) {
  170. mp_raise_msg(&mp_type_UnicodeError, NULL);
  171. }
  172. #endif
  173. return mp_obj_new_str(bufinfo.buf, bufinfo.len);
  174. }
  175. }
  176. }
  177. STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  178. (void)type_in;
  179. #if MICROPY_CPYTHON_COMPAT
  180. if (n_kw != 0) {
  181. mp_arg_error_unimpl_kw();
  182. }
  183. #else
  184. (void)n_kw;
  185. #endif
  186. if (n_args == 0) {
  187. return mp_const_empty_bytes;
  188. }
  189. if (mp_obj_is_str(args[0])) {
  190. if (n_args < 2 || n_args > 3) {
  191. goto wrong_args;
  192. }
  193. GET_STR_DATA_LEN(args[0], str_data, str_len);
  194. GET_STR_HASH(args[0], str_hash);
  195. if (str_hash == 0) {
  196. str_hash = qstr_compute_hash(str_data, str_len);
  197. }
  198. mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len));
  199. o->data = str_data;
  200. o->hash = str_hash;
  201. return MP_OBJ_FROM_PTR(o);
  202. }
  203. if (n_args > 1) {
  204. goto wrong_args;
  205. }
  206. if (mp_obj_is_small_int(args[0])) {
  207. mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
  208. if (len < 0) {
  209. mp_raise_ValueError(NULL);
  210. }
  211. vstr_t vstr;
  212. vstr_init_len(&vstr, len);
  213. memset(vstr.buf, 0, len);
  214. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  215. }
  216. // check if argument has the buffer protocol
  217. mp_buffer_info_t bufinfo;
  218. if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
  219. return mp_obj_new_bytes(bufinfo.buf, bufinfo.len);
  220. }
  221. vstr_t vstr;
  222. // Try to create array of exact len if initializer len is known
  223. mp_obj_t len_in = mp_obj_len_maybe(args[0]);
  224. if (len_in == MP_OBJ_NULL) {
  225. vstr_init(&vstr, 16);
  226. } else {
  227. mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
  228. vstr_init(&vstr, len);
  229. }
  230. mp_obj_iter_buf_t iter_buf;
  231. mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
  232. mp_obj_t item;
  233. while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  234. mp_int_t val = mp_obj_get_int(item);
  235. #if MICROPY_FULL_CHECKS
  236. if (val < 0 || val > 255) {
  237. mp_raise_ValueError("bytes value out of range");
  238. }
  239. #endif
  240. vstr_add_byte(&vstr, val);
  241. }
  242. return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
  243. wrong_args:
  244. mp_raise_TypeError("wrong number of arguments");
  245. }
  246. // like strstr but with specified length and allows \0 bytes
  247. // TODO replace with something more efficient/standard
  248. const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
  249. if (hlen >= nlen) {
  250. size_t str_index, str_index_end;
  251. if (direction > 0) {
  252. str_index = 0;
  253. str_index_end = hlen - nlen;
  254. } else {
  255. str_index = hlen - nlen;
  256. str_index_end = 0;
  257. }
  258. for (;;) {
  259. if (memcmp(&haystack[str_index], needle, nlen) == 0) {
  260. //found
  261. return haystack + str_index;
  262. }
  263. if (str_index == str_index_end) {
  264. //not found
  265. break;
  266. }
  267. str_index += direction;
  268. }
  269. }
  270. return NULL;
  271. }
  272. // Note: this function is used to check if an object is a str or bytes, which
  273. // works because both those types use it as their binary_op method. Revisit
  274. // mp_obj_is_str_or_bytes if this fact changes.
  275. mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  276. // check for modulo
  277. if (op == MP_BINARY_OP_MODULO) {
  278. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  279. mp_obj_t *args = &rhs_in;
  280. size_t n_args = 1;
  281. mp_obj_t dict = MP_OBJ_NULL;
  282. if (mp_obj_is_type(rhs_in, &mp_type_tuple)) {
  283. // TODO: Support tuple subclasses?
  284. mp_obj_tuple_get(rhs_in, &n_args, &args);
  285. } else if (mp_obj_is_type(rhs_in, &mp_type_dict)) {
  286. dict = rhs_in;
  287. }
  288. return str_modulo_format(lhs_in, n_args, args, dict);
  289. #else
  290. return MP_OBJ_NULL;
  291. #endif
  292. }
  293. // from now on we need lhs type and data, so extract them
  294. mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
  295. GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
  296. // check for multiply
  297. if (op == MP_BINARY_OP_MULTIPLY) {
  298. mp_int_t n;
  299. if (!mp_obj_get_int_maybe(rhs_in, &n)) {
  300. return MP_OBJ_NULL; // op not supported
  301. }
  302. if (n <= 0) {
  303. if (lhs_type == &mp_type_str) {
  304. return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
  305. } else {
  306. return mp_const_empty_bytes;
  307. }
  308. }
  309. vstr_t vstr;
  310. vstr_init_len(&vstr, lhs_len * n);
  311. mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
  312. return mp_obj_new_str_from_vstr(lhs_type, &vstr);
  313. }
  314. // From now on all operations allow:
  315. // - str with str
  316. // - bytes with bytes
  317. // - bytes with bytearray
  318. // - bytes with array.array
  319. // To do this efficiently we use the buffer protocol to extract the raw
  320. // data for the rhs, but only if the lhs is a bytes object.
  321. //
  322. // NOTE: CPython does not allow comparison between bytes ard array.array
  323. // (even if the array is of type 'b'), even though it allows addition of
  324. // such types. We are not compatible with this (we do allow comparison
  325. // of bytes with anything that has the buffer protocol). It would be
  326. // easy to "fix" this with a bit of extra logic below, but it costs code
  327. // size and execution time so we don't.
  328. const byte *rhs_data;
  329. size_t rhs_len;
  330. if (lhs_type == mp_obj_get_type(rhs_in)) {
  331. GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
  332. rhs_data = rhs_data_;
  333. rhs_len = rhs_len_;
  334. } else if (lhs_type == &mp_type_bytes) {
  335. mp_buffer_info_t bufinfo;
  336. if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
  337. return MP_OBJ_NULL; // op not supported
  338. }
  339. rhs_data = bufinfo.buf;
  340. rhs_len = bufinfo.len;
  341. } else {
  342. // LHS is str and RHS has an incompatible type
  343. // (except if operation is EQUAL, but that's handled by mp_obj_equal)
  344. bad_implicit_conversion(rhs_in);
  345. }
  346. switch (op) {
  347. case MP_BINARY_OP_ADD:
  348. case MP_BINARY_OP_INPLACE_ADD: {
  349. if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
  350. return rhs_in;
  351. }
  352. if (rhs_len == 0) {
  353. return lhs_in;
  354. }
  355. vstr_t vstr;
  356. vstr_init_len(&vstr, lhs_len + rhs_len);
  357. memcpy(vstr.buf, lhs_data, lhs_len);
  358. memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
  359. return mp_obj_new_str_from_vstr(lhs_type, &vstr);
  360. }
  361. case MP_BINARY_OP_CONTAINS:
  362. return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
  363. //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
  364. case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
  365. case MP_BINARY_OP_LESS:
  366. case MP_BINARY_OP_LESS_EQUAL:
  367. case MP_BINARY_OP_MORE:
  368. case MP_BINARY_OP_MORE_EQUAL:
  369. return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
  370. default:
  371. return MP_OBJ_NULL; // op not supported
  372. }
  373. }
  374. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  375. // objstrunicode defines own version
  376. const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
  377. mp_obj_t index, bool is_slice) {
  378. size_t index_val = mp_get_index(type, self_len, index, is_slice);
  379. return self_data + index_val;
  380. }
  381. #endif
  382. // This is used for both bytes and 8-bit strings. This is not used for unicode strings.
  383. STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
  384. mp_obj_type_t *type = mp_obj_get_type(self_in);
  385. GET_STR_DATA_LEN(self_in, self_data, self_len);
  386. if (value == MP_OBJ_SENTINEL) {
  387. // load
  388. #if MICROPY_PY_BUILTINS_SLICE
  389. if (mp_obj_is_type(index, &mp_type_slice)) {
  390. mp_bound_slice_t slice;
  391. if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
  392. mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported");
  393. }
  394. return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
  395. }
  396. #endif
  397. size_t index_val = mp_get_index(type, self_len, index, false);
  398. // If we have unicode enabled the type will always be bytes, so take the short cut.
  399. if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
  400. return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
  401. } else {
  402. return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1);
  403. }
  404. } else {
  405. return MP_OBJ_NULL; // op not supported
  406. }
  407. }
  408. STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
  409. mp_check_self(mp_obj_is_str_or_bytes(self_in));
  410. const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
  411. // get separation string
  412. GET_STR_DATA_LEN(self_in, sep_str, sep_len);
  413. // process args
  414. size_t seq_len;
  415. mp_obj_t *seq_items;
  416. if (!mp_obj_is_type(arg, &mp_type_list) && !mp_obj_is_type(arg, &mp_type_tuple)) {
  417. // arg is not a list nor a tuple, try to convert it to a list
  418. // TODO: Try to optimize?
  419. arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
  420. }
  421. mp_obj_get_array(arg, &seq_len, &seq_items);
  422. // count required length
  423. size_t required_len = 0;
  424. for (size_t i = 0; i < seq_len; i++) {
  425. if (mp_obj_get_type(seq_items[i]) != self_type) {
  426. mp_raise_TypeError(
  427. "join expects a list of str/bytes objects consistent with self object");
  428. }
  429. if (i > 0) {
  430. required_len += sep_len;
  431. }
  432. GET_STR_LEN(seq_items[i], l);
  433. required_len += l;
  434. }
  435. // make joined string
  436. vstr_t vstr;
  437. vstr_init_len(&vstr, required_len);
  438. byte *data = (byte*)vstr.buf;
  439. for (size_t i = 0; i < seq_len; i++) {
  440. if (i > 0) {
  441. memcpy(data, sep_str, sep_len);
  442. data += sep_len;
  443. }
  444. GET_STR_DATA_LEN(seq_items[i], s, l);
  445. memcpy(data, s, l);
  446. data += l;
  447. }
  448. // return joined string
  449. return mp_obj_new_str_from_vstr(self_type, &vstr);
  450. }
  451. MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
  452. mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
  453. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  454. mp_int_t splits = -1;
  455. mp_obj_t sep = mp_const_none;
  456. if (n_args > 1) {
  457. sep = args[1];
  458. if (n_args > 2) {
  459. splits = mp_obj_get_int(args[2]);
  460. }
  461. }
  462. mp_obj_t res = mp_obj_new_list(0, NULL);
  463. GET_STR_DATA_LEN(args[0], s, len);
  464. const byte *top = s + len;
  465. if (sep == mp_const_none) {
  466. // sep not given, so separate on whitespace
  467. // Initial whitespace is not counted as split, so we pre-do it
  468. while (s < top && unichar_isspace(*s)) s++;
  469. while (s < top && splits != 0) {
  470. const byte *start = s;
  471. while (s < top && !unichar_isspace(*s)) s++;
  472. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
  473. if (s >= top) {
  474. break;
  475. }
  476. while (s < top && unichar_isspace(*s)) s++;
  477. if (splits > 0) {
  478. splits--;
  479. }
  480. }
  481. if (s < top) {
  482. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
  483. }
  484. } else {
  485. // sep given
  486. if (mp_obj_get_type(sep) != self_type) {
  487. bad_implicit_conversion(sep);
  488. }
  489. size_t sep_len;
  490. const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
  491. if (sep_len == 0) {
  492. mp_raise_ValueError("empty separator");
  493. }
  494. for (;;) {
  495. const byte *start = s;
  496. for (;;) {
  497. if (splits == 0 || s + sep_len > top) {
  498. s = top;
  499. break;
  500. } else if (memcmp(s, sep_str, sep_len) == 0) {
  501. break;
  502. }
  503. s++;
  504. }
  505. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
  506. if (s >= top) {
  507. break;
  508. }
  509. s += sep_len;
  510. if (splits > 0) {
  511. splits--;
  512. }
  513. }
  514. }
  515. return res;
  516. }
  517. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
  518. #if MICROPY_PY_BUILTINS_STR_SPLITLINES
  519. STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  520. enum { ARG_keepends };
  521. static const mp_arg_t allowed_args[] = {
  522. { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
  523. };
  524. // parse args
  525. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  526. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  527. const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
  528. mp_obj_t res = mp_obj_new_list(0, NULL);
  529. GET_STR_DATA_LEN(pos_args[0], s, len);
  530. const byte *top = s + len;
  531. while (s < top) {
  532. const byte *start = s;
  533. size_t match = 0;
  534. while (s < top) {
  535. if (*s == '\n') {
  536. match = 1;
  537. break;
  538. } else if (*s == '\r') {
  539. if (s[1] == '\n') {
  540. match = 2;
  541. } else {
  542. match = 1;
  543. }
  544. break;
  545. }
  546. s++;
  547. }
  548. size_t sub_len = s - start;
  549. if (args[ARG_keepends].u_bool) {
  550. sub_len += match;
  551. }
  552. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
  553. s += match;
  554. }
  555. return res;
  556. }
  557. MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
  558. #endif
  559. STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
  560. if (n_args < 3) {
  561. // If we don't have split limit, it doesn't matter from which side
  562. // we split.
  563. return mp_obj_str_split(n_args, args);
  564. }
  565. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  566. mp_obj_t sep = args[1];
  567. GET_STR_DATA_LEN(args[0], s, len);
  568. mp_int_t splits = mp_obj_get_int(args[2]);
  569. if (splits < 0) {
  570. // Negative limit means no limit, so delegate to split().
  571. return mp_obj_str_split(n_args, args);
  572. }
  573. mp_int_t org_splits = splits;
  574. // Preallocate list to the max expected # of elements, as we
  575. // will fill it from the end.
  576. mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
  577. mp_int_t idx = splits;
  578. if (sep == mp_const_none) {
  579. mp_raise_NotImplementedError("rsplit(None,n)");
  580. } else {
  581. size_t sep_len;
  582. const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
  583. if (sep_len == 0) {
  584. mp_raise_ValueError("empty separator");
  585. }
  586. const byte *beg = s;
  587. const byte *last = s + len;
  588. for (;;) {
  589. s = last - sep_len;
  590. for (;;) {
  591. if (splits == 0 || s < beg) {
  592. break;
  593. } else if (memcmp(s, sep_str, sep_len) == 0) {
  594. break;
  595. }
  596. s--;
  597. }
  598. if (s < beg || splits == 0) {
  599. res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
  600. break;
  601. }
  602. res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
  603. last = s;
  604. splits--;
  605. }
  606. if (idx != 0) {
  607. // We split less parts than split limit, now go cleanup surplus
  608. size_t used = org_splits + 1 - idx;
  609. memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
  610. mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
  611. res->len = used;
  612. }
  613. }
  614. return MP_OBJ_FROM_PTR(res);
  615. }
  616. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
  617. STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) {
  618. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  619. mp_check_self(mp_obj_is_str_or_bytes(args[0]));
  620. // check argument type
  621. if (mp_obj_get_type(args[1]) != self_type) {
  622. bad_implicit_conversion(args[1]);
  623. }
  624. GET_STR_DATA_LEN(args[0], haystack, haystack_len);
  625. GET_STR_DATA_LEN(args[1], needle, needle_len);
  626. const byte *start = haystack;
  627. const byte *end = haystack + haystack_len;
  628. if (n_args >= 3 && args[2] != mp_const_none) {
  629. start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
  630. }
  631. if (n_args >= 4 && args[3] != mp_const_none) {
  632. end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
  633. }
  634. if (end < start) {
  635. goto out_error;
  636. }
  637. const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
  638. if (p == NULL) {
  639. out_error:
  640. // not found
  641. if (is_index) {
  642. mp_raise_ValueError("substring not found");
  643. } else {
  644. return MP_OBJ_NEW_SMALL_INT(-1);
  645. }
  646. } else {
  647. // found
  648. #if MICROPY_PY_BUILTINS_STR_UNICODE
  649. if (self_type == &mp_type_str) {
  650. return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
  651. }
  652. #endif
  653. return MP_OBJ_NEW_SMALL_INT(p - haystack);
  654. }
  655. }
  656. STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
  657. return str_finder(n_args, args, 1, false);
  658. }
  659. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
  660. STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
  661. return str_finder(n_args, args, -1, false);
  662. }
  663. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
  664. STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
  665. return str_finder(n_args, args, 1, true);
  666. }
  667. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
  668. STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
  669. return str_finder(n_args, args, -1, true);
  670. }
  671. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
  672. // TODO: (Much) more variety in args
  673. STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
  674. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  675. GET_STR_DATA_LEN(args[0], str, str_len);
  676. size_t prefix_len;
  677. const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
  678. const byte *start = str;
  679. if (n_args > 2) {
  680. start = str_index_to_ptr(self_type, str, str_len, args[2], true);
  681. }
  682. if (prefix_len + (start - str) > str_len) {
  683. return mp_const_false;
  684. }
  685. return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
  686. }
  687. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
  688. STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
  689. GET_STR_DATA_LEN(args[0], str, str_len);
  690. size_t suffix_len;
  691. const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
  692. if (n_args > 2) {
  693. mp_raise_NotImplementedError("start/end indices");
  694. }
  695. if (suffix_len > str_len) {
  696. return mp_const_false;
  697. }
  698. return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
  699. }
  700. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
  701. enum { LSTRIP, RSTRIP, STRIP };
  702. STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
  703. mp_check_self(mp_obj_is_str_or_bytes(args[0]));
  704. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  705. const byte *chars_to_del;
  706. uint chars_to_del_len;
  707. static const byte whitespace[] = " \t\n\r\v\f";
  708. if (n_args == 1) {
  709. chars_to_del = whitespace;
  710. chars_to_del_len = sizeof(whitespace) - 1;
  711. } else {
  712. if (mp_obj_get_type(args[1]) != self_type) {
  713. bad_implicit_conversion(args[1]);
  714. }
  715. GET_STR_DATA_LEN(args[1], s, l);
  716. chars_to_del = s;
  717. chars_to_del_len = l;
  718. }
  719. GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
  720. size_t first_good_char_pos = 0;
  721. bool first_good_char_pos_set = false;
  722. size_t last_good_char_pos = 0;
  723. size_t i = 0;
  724. int delta = 1;
  725. if (type == RSTRIP) {
  726. i = orig_str_len - 1;
  727. delta = -1;
  728. }
  729. for (size_t len = orig_str_len; len > 0; len--) {
  730. if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
  731. if (!first_good_char_pos_set) {
  732. first_good_char_pos_set = true;
  733. first_good_char_pos = i;
  734. if (type == LSTRIP) {
  735. last_good_char_pos = orig_str_len - 1;
  736. break;
  737. } else if (type == RSTRIP) {
  738. first_good_char_pos = 0;
  739. last_good_char_pos = i;
  740. break;
  741. }
  742. }
  743. last_good_char_pos = i;
  744. }
  745. i += delta;
  746. }
  747. if (!first_good_char_pos_set) {
  748. // string is all whitespace, return ''
  749. if (self_type == &mp_type_str) {
  750. return MP_OBJ_NEW_QSTR(MP_QSTR_);
  751. } else {
  752. return mp_const_empty_bytes;
  753. }
  754. }
  755. assert(last_good_char_pos >= first_good_char_pos);
  756. //+1 to accommodate the last character
  757. size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
  758. if (stripped_len == orig_str_len) {
  759. // If nothing was stripped, don't bother to dup original string
  760. // TODO: watch out for this case when we'll get to bytearray.strip()
  761. assert(first_good_char_pos == 0);
  762. return args[0];
  763. }
  764. return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
  765. }
  766. STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
  767. return str_uni_strip(STRIP, n_args, args);
  768. }
  769. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
  770. STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
  771. return str_uni_strip(LSTRIP, n_args, args);
  772. }
  773. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
  774. STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
  775. return str_uni_strip(RSTRIP, n_args, args);
  776. }
  777. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
  778. #if MICROPY_PY_BUILTINS_STR_CENTER
  779. STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
  780. GET_STR_DATA_LEN(str_in, str, str_len);
  781. mp_uint_t width = mp_obj_get_int(width_in);
  782. if (str_len >= width) {
  783. return str_in;
  784. }
  785. vstr_t vstr;
  786. vstr_init_len(&vstr, width);
  787. memset(vstr.buf, ' ', width);
  788. int left = (width - str_len) / 2;
  789. memcpy(vstr.buf + left, str, str_len);
  790. return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
  791. }
  792. MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
  793. #endif
  794. // Takes an int arg, but only parses unsigned numbers, and only changes
  795. // *num if at least one digit was parsed.
  796. STATIC const char *str_to_int(const char *str, const char *top, int *num) {
  797. if (str < top && '0' <= *str && *str <= '9') {
  798. *num = 0;
  799. do {
  800. *num = *num * 10 + (*str - '0');
  801. str++;
  802. }
  803. while (str < top && '0' <= *str && *str <= '9');
  804. }
  805. return str;
  806. }
  807. STATIC bool isalignment(char ch) {
  808. return ch && strchr("<>=^", ch) != NULL;
  809. }
  810. STATIC bool istype(char ch) {
  811. return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
  812. }
  813. STATIC bool arg_looks_integer(mp_obj_t arg) {
  814. return mp_obj_is_type(arg, &mp_type_bool) || mp_obj_is_int(arg);
  815. }
  816. STATIC bool arg_looks_numeric(mp_obj_t arg) {
  817. return arg_looks_integer(arg)
  818. #if MICROPY_PY_BUILTINS_FLOAT
  819. || mp_obj_is_float(arg)
  820. #endif
  821. ;
  822. }
  823. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  824. STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
  825. #if MICROPY_PY_BUILTINS_FLOAT
  826. if (mp_obj_is_float(arg)) {
  827. return mp_obj_new_int_from_float(mp_obj_float_get(arg));
  828. }
  829. #endif
  830. return arg;
  831. }
  832. #endif
  833. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  834. STATIC NORETURN void terse_str_format_value_error(void) {
  835. mp_raise_ValueError("bad format string");
  836. }
  837. #else
  838. // define to nothing to improve coverage
  839. #define terse_str_format_value_error()
  840. #endif
  841. STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  842. vstr_t vstr;
  843. mp_print_t print;
  844. vstr_init_print(&vstr, 16, &print);
  845. for (; str < top; str++) {
  846. if (*str == '}') {
  847. str++;
  848. if (str < top && *str == '}') {
  849. vstr_add_byte(&vstr, '}');
  850. continue;
  851. }
  852. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  853. terse_str_format_value_error();
  854. } else {
  855. mp_raise_ValueError("single '}' encountered in format string");
  856. }
  857. }
  858. if (*str != '{') {
  859. vstr_add_byte(&vstr, *str);
  860. continue;
  861. }
  862. str++;
  863. if (str < top && *str == '{') {
  864. vstr_add_byte(&vstr, '{');
  865. continue;
  866. }
  867. // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
  868. const char *field_name = NULL;
  869. const char *field_name_top = NULL;
  870. char conversion = '\0';
  871. const char *format_spec = NULL;
  872. if (str < top && *str != '}' && *str != '!' && *str != ':') {
  873. field_name = (const char *)str;
  874. while (str < top && *str != '}' && *str != '!' && *str != ':') {
  875. ++str;
  876. }
  877. field_name_top = (const char *)str;
  878. }
  879. // conversion ::= "r" | "s"
  880. if (str < top && *str == '!') {
  881. str++;
  882. if (str < top && (*str == 'r' || *str == 's')) {
  883. conversion = *str++;
  884. } else {
  885. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  886. terse_str_format_value_error();
  887. } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
  888. mp_raise_ValueError("bad conversion specifier");
  889. } else {
  890. if (str >= top) {
  891. mp_raise_ValueError(
  892. "end of format while looking for conversion specifier");
  893. } else {
  894. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  895. "unknown conversion specifier %c", *str));
  896. }
  897. }
  898. }
  899. }
  900. if (str < top && *str == ':') {
  901. str++;
  902. // {:} is the same as {}, which is the same as {!s}
  903. // This makes a difference when passing in a True or False
  904. // '{}'.format(True) returns 'True'
  905. // '{:d}'.format(True) returns '1'
  906. // So we treat {:} as {} and this later gets treated to be {!s}
  907. if (*str != '}') {
  908. format_spec = str;
  909. for (int nest = 1; str < top;) {
  910. if (*str == '{') {
  911. ++nest;
  912. } else if (*str == '}') {
  913. if (--nest == 0) {
  914. break;
  915. }
  916. }
  917. ++str;
  918. }
  919. }
  920. }
  921. if (str >= top) {
  922. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  923. terse_str_format_value_error();
  924. } else {
  925. mp_raise_ValueError("unmatched '{' in format");
  926. }
  927. }
  928. if (*str != '}') {
  929. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  930. terse_str_format_value_error();
  931. } else {
  932. mp_raise_ValueError("expected ':' after format specifier");
  933. }
  934. }
  935. mp_obj_t arg = mp_const_none;
  936. if (field_name) {
  937. int index = 0;
  938. if (MP_LIKELY(unichar_isdigit(*field_name))) {
  939. if (*arg_i > 0) {
  940. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  941. terse_str_format_value_error();
  942. } else {
  943. mp_raise_ValueError(
  944. "can't switch from automatic field numbering to manual field specification");
  945. }
  946. }
  947. field_name = str_to_int(field_name, field_name_top, &index);
  948. if ((uint)index >= n_args - 1) {
  949. mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
  950. }
  951. arg = args[index + 1];
  952. *arg_i = -1;
  953. } else {
  954. const char *lookup;
  955. for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
  956. mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
  957. field_name = lookup;
  958. mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
  959. if (key_elem == NULL) {
  960. nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
  961. }
  962. arg = key_elem->value;
  963. }
  964. if (field_name < field_name_top) {
  965. mp_raise_NotImplementedError("attributes not supported yet");
  966. }
  967. } else {
  968. if (*arg_i < 0) {
  969. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  970. terse_str_format_value_error();
  971. } else {
  972. mp_raise_ValueError(
  973. "can't switch from manual field specification to automatic field numbering");
  974. }
  975. }
  976. if ((uint)*arg_i >= n_args - 1) {
  977. mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
  978. }
  979. arg = args[(*arg_i) + 1];
  980. (*arg_i)++;
  981. }
  982. if (!format_spec && !conversion) {
  983. conversion = 's';
  984. }
  985. if (conversion) {
  986. mp_print_kind_t print_kind;
  987. if (conversion == 's') {
  988. print_kind = PRINT_STR;
  989. } else {
  990. assert(conversion == 'r');
  991. print_kind = PRINT_REPR;
  992. }
  993. vstr_t arg_vstr;
  994. mp_print_t arg_print;
  995. vstr_init_print(&arg_vstr, 16, &arg_print);
  996. mp_obj_print_helper(&arg_print, arg, print_kind);
  997. arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
  998. }
  999. char fill = '\0';
  1000. char align = '\0';
  1001. int width = -1;
  1002. int precision = -1;
  1003. char type = '\0';
  1004. int flags = 0;
  1005. if (format_spec) {
  1006. // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
  1007. //
  1008. // [[fill]align][sign][#][0][width][,][.precision][type]
  1009. // fill ::= <any character>
  1010. // align ::= "<" | ">" | "=" | "^"
  1011. // sign ::= "+" | "-" | " "
  1012. // width ::= integer
  1013. // precision ::= integer
  1014. // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  1015. // recursively call the formatter to format any nested specifiers
  1016. MP_STACK_CHECK();
  1017. vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
  1018. const char *s = vstr_null_terminated_str(&format_spec_vstr);
  1019. const char *stop = s + format_spec_vstr.len;
  1020. if (isalignment(*s)) {
  1021. align = *s++;
  1022. } else if (*s && isalignment(s[1])) {
  1023. fill = *s++;
  1024. align = *s++;
  1025. }
  1026. if (*s == '+' || *s == '-' || *s == ' ') {
  1027. if (*s == '+') {
  1028. flags |= PF_FLAG_SHOW_SIGN;
  1029. } else if (*s == ' ') {
  1030. flags |= PF_FLAG_SPACE_SIGN;
  1031. }
  1032. s++;
  1033. }
  1034. if (*s == '#') {
  1035. flags |= PF_FLAG_SHOW_PREFIX;
  1036. s++;
  1037. }
  1038. if (*s == '0') {
  1039. if (!align) {
  1040. align = '=';
  1041. }
  1042. if (!fill) {
  1043. fill = '0';
  1044. }
  1045. }
  1046. s = str_to_int(s, stop, &width);
  1047. if (*s == ',') {
  1048. flags |= PF_FLAG_SHOW_COMMA;
  1049. s++;
  1050. }
  1051. if (*s == '.') {
  1052. s++;
  1053. s = str_to_int(s, stop, &precision);
  1054. }
  1055. if (istype(*s)) {
  1056. type = *s++;
  1057. }
  1058. if (*s) {
  1059. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1060. terse_str_format_value_error();
  1061. } else {
  1062. mp_raise_ValueError("invalid format specifier");
  1063. }
  1064. }
  1065. vstr_clear(&format_spec_vstr);
  1066. }
  1067. if (!align) {
  1068. if (arg_looks_numeric(arg)) {
  1069. align = '>';
  1070. } else {
  1071. align = '<';
  1072. }
  1073. }
  1074. if (!fill) {
  1075. fill = ' ';
  1076. }
  1077. if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
  1078. if (type == 's') {
  1079. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1080. terse_str_format_value_error();
  1081. } else {
  1082. mp_raise_ValueError("sign not allowed in string format specifier");
  1083. }
  1084. }
  1085. if (type == 'c') {
  1086. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1087. terse_str_format_value_error();
  1088. } else {
  1089. mp_raise_ValueError(
  1090. "sign not allowed with integer format specifier 'c'");
  1091. }
  1092. }
  1093. }
  1094. switch (align) {
  1095. case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
  1096. case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
  1097. case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
  1098. }
  1099. if (arg_looks_integer(arg)) {
  1100. switch (type) {
  1101. case 'b':
  1102. mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
  1103. continue;
  1104. case 'c':
  1105. {
  1106. char ch = mp_obj_get_int(arg);
  1107. mp_print_strn(&print, &ch, 1, flags, fill, width);
  1108. continue;
  1109. }
  1110. case '\0': // No explicit format type implies 'd'
  1111. case 'n': // I don't think we support locales in uPy so use 'd'
  1112. case 'd':
  1113. mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
  1114. continue;
  1115. case 'o':
  1116. if (flags & PF_FLAG_SHOW_PREFIX) {
  1117. flags |= PF_FLAG_SHOW_OCTAL_LETTER;
  1118. }
  1119. mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
  1120. continue;
  1121. case 'X':
  1122. case 'x':
  1123. mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
  1124. continue;
  1125. case 'e':
  1126. case 'E':
  1127. case 'f':
  1128. case 'F':
  1129. case 'g':
  1130. case 'G':
  1131. case '%':
  1132. // The floating point formatters all work with anything that
  1133. // looks like an integer
  1134. break;
  1135. default:
  1136. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1137. terse_str_format_value_error();
  1138. } else {
  1139. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  1140. "unknown format code '%c' for object of type '%s'",
  1141. type, mp_obj_get_type_str(arg)));
  1142. }
  1143. }
  1144. }
  1145. // NOTE: no else here. We need the e, f, g etc formats for integer
  1146. // arguments (from above if) to take this if.
  1147. if (arg_looks_numeric(arg)) {
  1148. if (!type) {
  1149. // Even though the docs say that an unspecified type is the same
  1150. // as 'g', there is one subtle difference, when the exponent
  1151. // is one less than the precision.
  1152. //
  1153. // '{:10.1}'.format(0.0) ==> '0e+00'
  1154. // '{:10.1g}'.format(0.0) ==> '0'
  1155. //
  1156. // TODO: Figure out how to deal with this.
  1157. //
  1158. // A proper solution would involve adding a special flag
  1159. // or something to format_float, and create a format_double
  1160. // to deal with doubles. In order to fix this when using
  1161. // sprintf, we'd need to use the e format and tweak the
  1162. // returned result to strip trailing zeros like the g format
  1163. // does.
  1164. //
  1165. // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
  1166. // but with 1.e2 you get 1e+02 and 1.00e+02
  1167. //
  1168. // Stripping the trailing 0's (like g) does would make the
  1169. // e format give us the right format.
  1170. //
  1171. // CPython sources say:
  1172. // Omitted type specifier. Behaves in the same way as repr(x)
  1173. // and str(x) if no precision is given, else like 'g', but with
  1174. // at least one digit after the decimal point. */
  1175. type = 'g';
  1176. }
  1177. if (type == 'n') {
  1178. type = 'g';
  1179. }
  1180. switch (type) {
  1181. #if MICROPY_PY_BUILTINS_FLOAT
  1182. case 'e':
  1183. case 'E':
  1184. case 'f':
  1185. case 'F':
  1186. case 'g':
  1187. case 'G':
  1188. mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
  1189. break;
  1190. case '%':
  1191. flags |= PF_FLAG_ADD_PERCENT;
  1192. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  1193. #define F100 100.0F
  1194. #else
  1195. #define F100 100.0
  1196. #endif
  1197. mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
  1198. #undef F100
  1199. break;
  1200. #endif
  1201. default:
  1202. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1203. terse_str_format_value_error();
  1204. } else {
  1205. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  1206. "unknown format code '%c' for object of type '%s'",
  1207. type, mp_obj_get_type_str(arg)));
  1208. }
  1209. }
  1210. } else {
  1211. // arg doesn't look like a number
  1212. if (align == '=') {
  1213. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1214. terse_str_format_value_error();
  1215. } else {
  1216. mp_raise_ValueError(
  1217. "'=' alignment not allowed in string format specifier");
  1218. }
  1219. }
  1220. switch (type) {
  1221. case '\0': // no explicit format type implies 's'
  1222. case 's': {
  1223. size_t slen;
  1224. const char *s = mp_obj_str_get_data(arg, &slen);
  1225. if (precision < 0) {
  1226. precision = slen;
  1227. }
  1228. if (slen > (size_t)precision) {
  1229. slen = precision;
  1230. }
  1231. mp_print_strn(&print, s, slen, flags, fill, width);
  1232. break;
  1233. }
  1234. default:
  1235. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1236. terse_str_format_value_error();
  1237. } else {
  1238. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  1239. "unknown format code '%c' for object of type '%s'",
  1240. type, mp_obj_get_type_str(arg)));
  1241. }
  1242. }
  1243. }
  1244. }
  1245. return vstr;
  1246. }
  1247. mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  1248. mp_check_self(mp_obj_is_str_or_bytes(args[0]));
  1249. GET_STR_DATA_LEN(args[0], str, len);
  1250. int arg_i = 0;
  1251. vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
  1252. return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr);
  1253. }
  1254. MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
  1255. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  1256. STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
  1257. mp_check_self(mp_obj_is_str_or_bytes(pattern));
  1258. GET_STR_DATA_LEN(pattern, str, len);
  1259. const byte *start_str = str;
  1260. bool is_bytes = mp_obj_is_type(pattern, &mp_type_bytes);
  1261. size_t arg_i = 0;
  1262. vstr_t vstr;
  1263. mp_print_t print;
  1264. vstr_init_print(&vstr, 16, &print);
  1265. for (const byte *top = str + len; str < top; str++) {
  1266. mp_obj_t arg = MP_OBJ_NULL;
  1267. if (*str != '%') {
  1268. vstr_add_byte(&vstr, *str);
  1269. continue;
  1270. }
  1271. if (++str >= top) {
  1272. goto incomplete_format;
  1273. }
  1274. if (*str == '%') {
  1275. vstr_add_byte(&vstr, '%');
  1276. continue;
  1277. }
  1278. // Dictionary value lookup
  1279. if (*str == '(') {
  1280. if (dict == MP_OBJ_NULL) {
  1281. mp_raise_TypeError("format needs a dict");
  1282. }
  1283. arg_i = 1; // we used up the single dict argument
  1284. const byte *key = ++str;
  1285. while (*str != ')') {
  1286. if (str >= top) {
  1287. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1288. terse_str_format_value_error();
  1289. } else {
  1290. mp_raise_ValueError("incomplete format key");
  1291. }
  1292. }
  1293. ++str;
  1294. }
  1295. mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key);
  1296. arg = mp_obj_dict_get(dict, k_obj);
  1297. str++;
  1298. }
  1299. int flags = 0;
  1300. char fill = ' ';
  1301. int alt = 0;
  1302. while (str < top) {
  1303. if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
  1304. else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
  1305. else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
  1306. else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
  1307. else if (*str == '0') {
  1308. flags |= PF_FLAG_PAD_AFTER_SIGN;
  1309. fill = '0';
  1310. } else break;
  1311. str++;
  1312. }
  1313. // parse width, if it exists
  1314. int width = 0;
  1315. if (str < top) {
  1316. if (*str == '*') {
  1317. if (arg_i >= n_args) {
  1318. goto not_enough_args;
  1319. }
  1320. width = mp_obj_get_int(args[arg_i++]);
  1321. str++;
  1322. } else {
  1323. str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
  1324. }
  1325. }
  1326. int prec = -1;
  1327. if (str < top && *str == '.') {
  1328. if (++str < top) {
  1329. if (*str == '*') {
  1330. if (arg_i >= n_args) {
  1331. goto not_enough_args;
  1332. }
  1333. prec = mp_obj_get_int(args[arg_i++]);
  1334. str++;
  1335. } else {
  1336. prec = 0;
  1337. str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
  1338. }
  1339. }
  1340. }
  1341. if (str >= top) {
  1342. incomplete_format:
  1343. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1344. terse_str_format_value_error();
  1345. } else {
  1346. mp_raise_ValueError("incomplete format");
  1347. }
  1348. }
  1349. // Tuple value lookup
  1350. if (arg == MP_OBJ_NULL) {
  1351. if (arg_i >= n_args) {
  1352. not_enough_args:
  1353. mp_raise_TypeError("format string needs more arguments");
  1354. }
  1355. arg = args[arg_i++];
  1356. }
  1357. switch (*str) {
  1358. case 'c':
  1359. if (mp_obj_is_str(arg)) {
  1360. size_t slen;
  1361. const char *s = mp_obj_str_get_data(arg, &slen);
  1362. if (slen != 1) {
  1363. mp_raise_TypeError("%%c needs int or char");
  1364. }
  1365. mp_print_strn(&print, s, 1, flags, ' ', width);
  1366. } else if (arg_looks_integer(arg)) {
  1367. char ch = mp_obj_get_int(arg);
  1368. mp_print_strn(&print, &ch, 1, flags, ' ', width);
  1369. } else {
  1370. mp_raise_TypeError("integer needed");
  1371. }
  1372. break;
  1373. case 'd':
  1374. case 'i':
  1375. case 'u':
  1376. mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
  1377. break;
  1378. #if MICROPY_PY_BUILTINS_FLOAT
  1379. case 'e':
  1380. case 'E':
  1381. case 'f':
  1382. case 'F':
  1383. case 'g':
  1384. case 'G':
  1385. mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
  1386. break;
  1387. #endif
  1388. case 'o':
  1389. if (alt) {
  1390. flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
  1391. }
  1392. mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
  1393. break;
  1394. case 'r':
  1395. case 's':
  1396. {
  1397. vstr_t arg_vstr;
  1398. mp_print_t arg_print;
  1399. vstr_init_print(&arg_vstr, 16, &arg_print);
  1400. mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
  1401. if (print_kind == PRINT_STR && is_bytes && mp_obj_is_type(arg, &mp_type_bytes)) {
  1402. // If we have something like b"%s" % b"1", bytes arg should be
  1403. // printed undecorated.
  1404. print_kind = PRINT_RAW;
  1405. }
  1406. mp_obj_print_helper(&arg_print, arg, print_kind);
  1407. uint vlen = arg_vstr.len;
  1408. if (prec < 0) {
  1409. prec = vlen;
  1410. }
  1411. if (vlen > (uint)prec) {
  1412. vlen = prec;
  1413. }
  1414. mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
  1415. vstr_clear(&arg_vstr);
  1416. break;
  1417. }
  1418. case 'X':
  1419. case 'x':
  1420. mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
  1421. break;
  1422. default:
  1423. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1424. terse_str_format_value_error();
  1425. } else {
  1426. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
  1427. "unsupported format character '%c' (0x%x) at index %d",
  1428. *str, *str, str - start_str));
  1429. }
  1430. }
  1431. }
  1432. if (arg_i != n_args) {
  1433. mp_raise_TypeError("format string didn't convert all arguments");
  1434. }
  1435. return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
  1436. }
  1437. #endif
  1438. // The implementation is optimized, returning the original string if there's
  1439. // nothing to replace.
  1440. STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
  1441. mp_check_self(mp_obj_is_str_or_bytes(args[0]));
  1442. mp_int_t max_rep = -1;
  1443. if (n_args == 4) {
  1444. max_rep = mp_obj_get_int(args[3]);
  1445. if (max_rep == 0) {
  1446. return args[0];
  1447. } else if (max_rep < 0) {
  1448. max_rep = -1;
  1449. }
  1450. }
  1451. // if max_rep is still -1 by this point we will need to do all possible replacements
  1452. // check argument types
  1453. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  1454. if (mp_obj_get_type(args[1]) != self_type) {
  1455. bad_implicit_conversion(args[1]);
  1456. }
  1457. if (mp_obj_get_type(args[2]) != self_type) {
  1458. bad_implicit_conversion(args[2]);
  1459. }
  1460. // extract string data
  1461. GET_STR_DATA_LEN(args[0], str, str_len);
  1462. GET_STR_DATA_LEN(args[1], old, old_len);
  1463. GET_STR_DATA_LEN(args[2], new, new_len);
  1464. // old won't exist in str if it's longer, so nothing to replace
  1465. if (old_len > str_len) {
  1466. return args[0];
  1467. }
  1468. // data for the replaced string
  1469. byte *data = NULL;
  1470. vstr_t vstr;
  1471. // do 2 passes over the string:
  1472. // first pass computes the required length of the replaced string
  1473. // second pass does the replacements
  1474. for (;;) {
  1475. size_t replaced_str_index = 0;
  1476. size_t num_replacements_done = 0;
  1477. const byte *old_occurrence;
  1478. const byte *offset_ptr = str;
  1479. size_t str_len_remain = str_len;
  1480. if (old_len == 0) {
  1481. // if old_str is empty, copy new_str to start of replaced string
  1482. // copy the replacement string
  1483. if (data != NULL) {
  1484. memcpy(data, new, new_len);
  1485. }
  1486. replaced_str_index += new_len;
  1487. num_replacements_done++;
  1488. }
  1489. while (num_replacements_done != (size_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
  1490. if (old_len == 0) {
  1491. old_occurrence += 1;
  1492. }
  1493. // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
  1494. if (data != NULL) {
  1495. memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
  1496. }
  1497. replaced_str_index += old_occurrence - offset_ptr;
  1498. // copy the replacement string
  1499. if (data != NULL) {
  1500. memcpy(data + replaced_str_index, new, new_len);
  1501. }
  1502. replaced_str_index += new_len;
  1503. offset_ptr = old_occurrence + old_len;
  1504. str_len_remain = str + str_len - offset_ptr;
  1505. num_replacements_done++;
  1506. }
  1507. // copy from just after end of last occurrence of to-be-replaced string to end of old string
  1508. if (data != NULL) {
  1509. memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
  1510. }
  1511. replaced_str_index += str_len_remain;
  1512. if (data == NULL) {
  1513. // first pass
  1514. if (num_replacements_done == 0) {
  1515. // no substr found, return original string
  1516. return args[0];
  1517. } else {
  1518. // substr found, allocate new string
  1519. vstr_init_len(&vstr, replaced_str_index);
  1520. data = (byte*)vstr.buf;
  1521. assert(data != NULL);
  1522. }
  1523. } else {
  1524. // second pass, we are done
  1525. break;
  1526. }
  1527. }
  1528. return mp_obj_new_str_from_vstr(self_type, &vstr);
  1529. }
  1530. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
  1531. #if MICROPY_PY_BUILTINS_STR_COUNT
  1532. STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
  1533. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  1534. mp_check_self(mp_obj_is_str_or_bytes(args[0]));
  1535. // check argument type
  1536. if (mp_obj_get_type(args[1]) != self_type) {
  1537. bad_implicit_conversion(args[1]);
  1538. }
  1539. GET_STR_DATA_LEN(args[0], haystack, haystack_len);
  1540. GET_STR_DATA_LEN(args[1], needle, needle_len);
  1541. const byte *start = haystack;
  1542. const byte *end = haystack + haystack_len;
  1543. if (n_args >= 3 && args[2] != mp_const_none) {
  1544. start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
  1545. }
  1546. if (n_args >= 4 && args[3] != mp_const_none) {
  1547. end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
  1548. }
  1549. // if needle_len is zero then we count each gap between characters as an occurrence
  1550. if (needle_len == 0) {
  1551. return MP_OBJ_NEW_SMALL_INT(utf8_charlen(start, end - start) + 1);
  1552. }
  1553. // count the occurrences
  1554. mp_int_t num_occurrences = 0;
  1555. for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
  1556. if (memcmp(haystack_ptr, needle, needle_len) == 0) {
  1557. num_occurrences++;
  1558. haystack_ptr += needle_len;
  1559. } else {
  1560. haystack_ptr = utf8_next_char(haystack_ptr);
  1561. }
  1562. }
  1563. return MP_OBJ_NEW_SMALL_INT(num_occurrences);
  1564. }
  1565. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
  1566. #endif
  1567. #if MICROPY_PY_BUILTINS_STR_PARTITION
  1568. STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
  1569. mp_check_self(mp_obj_is_str_or_bytes(self_in));
  1570. mp_obj_type_t *self_type = mp_obj_get_type(self_in);
  1571. if (self_type != mp_obj_get_type(arg)) {
  1572. bad_implicit_conversion(arg);
  1573. }
  1574. GET_STR_DATA_LEN(self_in, str, str_len);
  1575. GET_STR_DATA_LEN(arg, sep, sep_len);
  1576. if (sep_len == 0) {
  1577. mp_raise_ValueError("empty separator");
  1578. }
  1579. mp_obj_t result[3];
  1580. if (self_type == &mp_type_str) {
  1581. result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1582. result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1583. result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1584. } else {
  1585. result[0] = mp_const_empty_bytes;
  1586. result[1] = mp_const_empty_bytes;
  1587. result[2] = mp_const_empty_bytes;
  1588. }
  1589. if (direction > 0) {
  1590. result[0] = self_in;
  1591. } else {
  1592. result[2] = self_in;
  1593. }
  1594. const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
  1595. if (position_ptr != NULL) {
  1596. size_t position = position_ptr - str;
  1597. result[0] = mp_obj_new_str_of_type(self_type, str, position);
  1598. result[1] = arg;
  1599. result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
  1600. }
  1601. return mp_obj_new_tuple(3, result);
  1602. }
  1603. STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
  1604. return str_partitioner(self_in, arg, 1);
  1605. }
  1606. MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
  1607. STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
  1608. return str_partitioner(self_in, arg, -1);
  1609. }
  1610. MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
  1611. #endif
  1612. // Supposedly not too critical operations, so optimize for code size
  1613. STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
  1614. GET_STR_DATA_LEN(self_in, self_data, self_len);
  1615. vstr_t vstr;
  1616. vstr_init_len(&vstr, self_len);
  1617. byte *data = (byte*)vstr.buf;
  1618. for (size_t i = 0; i < self_len; i++) {
  1619. *data++ = op(*self_data++);
  1620. }
  1621. return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
  1622. }
  1623. STATIC mp_obj_t str_lower(mp_obj_t self_in) {
  1624. return str_caseconv(unichar_tolower, self_in);
  1625. }
  1626. MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
  1627. STATIC mp_obj_t str_upper(mp_obj_t self_in) {
  1628. return str_caseconv(unichar_toupper, self_in);
  1629. }
  1630. MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
  1631. STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
  1632. GET_STR_DATA_LEN(self_in, self_data, self_len);
  1633. if (self_len == 0) {
  1634. return mp_const_false; // default to False for empty str
  1635. }
  1636. if (f != unichar_isupper && f != unichar_islower) {
  1637. for (size_t i = 0; i < self_len; i++) {
  1638. if (!f(*self_data++)) {
  1639. return mp_const_false;
  1640. }
  1641. }
  1642. } else {
  1643. bool contains_alpha = false;
  1644. for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
  1645. if (unichar_isalpha(*self_data++)) {
  1646. contains_alpha = true;
  1647. if (!f(*(self_data - 1))) { // -1 because we already incremented above
  1648. return mp_const_false;
  1649. }
  1650. }
  1651. }
  1652. if (!contains_alpha) {
  1653. return mp_const_false;
  1654. }
  1655. }
  1656. return mp_const_true;
  1657. }
  1658. STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
  1659. return str_uni_istype(unichar_isspace, self_in);
  1660. }
  1661. MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
  1662. STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
  1663. return str_uni_istype(unichar_isalpha, self_in);
  1664. }
  1665. MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
  1666. STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
  1667. return str_uni_istype(unichar_isdigit, self_in);
  1668. }
  1669. MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
  1670. STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
  1671. return str_uni_istype(unichar_isupper, self_in);
  1672. }
  1673. MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
  1674. STATIC mp_obj_t str_islower(mp_obj_t self_in) {
  1675. return str_uni_istype(unichar_islower, self_in);
  1676. }
  1677. MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
  1678. #if MICROPY_CPYTHON_COMPAT
  1679. // These methods are superfluous in the presence of str() and bytes()
  1680. // constructors.
  1681. // TODO: should accept kwargs too
  1682. STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
  1683. mp_obj_t new_args[2];
  1684. if (n_args == 1) {
  1685. new_args[0] = args[0];
  1686. new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
  1687. args = new_args;
  1688. n_args++;
  1689. }
  1690. return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
  1691. }
  1692. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
  1693. // TODO: should accept kwargs too
  1694. STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
  1695. mp_obj_t new_args[2];
  1696. if (n_args == 1) {
  1697. new_args[0] = args[0];
  1698. new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
  1699. args = new_args;
  1700. n_args++;
  1701. }
  1702. return bytes_make_new(NULL, n_args, 0, args);
  1703. }
  1704. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
  1705. #endif
  1706. mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  1707. if (flags == MP_BUFFER_READ) {
  1708. GET_STR_DATA_LEN(self_in, str_data, str_len);
  1709. bufinfo->buf = (void*)str_data;
  1710. bufinfo->len = str_len;
  1711. bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
  1712. return 0;
  1713. } else {
  1714. // can't write to a string
  1715. bufinfo->buf = NULL;
  1716. bufinfo->len = 0;
  1717. bufinfo->typecode = -1;
  1718. return 1;
  1719. }
  1720. }
  1721. STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
  1722. #if MICROPY_CPYTHON_COMPAT
  1723. { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
  1724. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  1725. // If we have separate unicode type, then here we have methods only
  1726. // for bytes type, and it should not have encode() methods. Otherwise,
  1727. // we have non-compliant-but-practical bytestring type, which shares
  1728. // method table with bytes, so they both have encode() and decode()
  1729. // methods (which should do type checking at runtime).
  1730. { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
  1731. #endif
  1732. #endif
  1733. { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
  1734. { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
  1735. { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
  1736. { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
  1737. { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
  1738. { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
  1739. #if MICROPY_PY_BUILTINS_STR_SPLITLINES
  1740. { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
  1741. #endif
  1742. { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
  1743. { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
  1744. { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
  1745. { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
  1746. { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
  1747. { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
  1748. { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
  1749. { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
  1750. #if MICROPY_PY_BUILTINS_STR_COUNT
  1751. { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
  1752. #endif
  1753. #if MICROPY_PY_BUILTINS_STR_PARTITION
  1754. { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
  1755. { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
  1756. #endif
  1757. #if MICROPY_PY_BUILTINS_STR_CENTER
  1758. { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
  1759. #endif
  1760. { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
  1761. { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
  1762. { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
  1763. { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
  1764. { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
  1765. { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
  1766. { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
  1767. };
  1768. STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
  1769. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  1770. STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
  1771. const mp_obj_type_t mp_type_str = {
  1772. { &mp_type_type },
  1773. .name = MP_QSTR_str,
  1774. .print = str_print,
  1775. .make_new = mp_obj_str_make_new,
  1776. .binary_op = mp_obj_str_binary_op,
  1777. .subscr = bytes_subscr,
  1778. .getiter = mp_obj_new_str_iterator,
  1779. .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
  1780. .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
  1781. };
  1782. #endif
  1783. // Reuses most of methods from str
  1784. const mp_obj_type_t mp_type_bytes = {
  1785. { &mp_type_type },
  1786. .name = MP_QSTR_bytes,
  1787. .print = str_print,
  1788. .make_new = bytes_make_new,
  1789. .binary_op = mp_obj_str_binary_op,
  1790. .subscr = bytes_subscr,
  1791. .getiter = mp_obj_new_bytes_iterator,
  1792. .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
  1793. .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
  1794. };
  1795. // The zero-length bytes object, with data that includes a null-terminating byte
  1796. const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""};
  1797. // Create a str/bytes object using the given data. New memory is allocated and
  1798. // the data is copied across. This function should only be used if the type is bytes,
  1799. // or if the type is str and the string data is known to be not interned.
  1800. mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len) {
  1801. mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
  1802. o->base.type = type;
  1803. o->len = len;
  1804. if (data) {
  1805. o->hash = qstr_compute_hash(data, len);
  1806. byte *p = m_new(byte, len + 1);
  1807. o->data = p;
  1808. memcpy(p, data, len * sizeof(byte));
  1809. p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
  1810. }
  1811. return MP_OBJ_FROM_PTR(o);
  1812. }
  1813. // Create a str/bytes object using the given data. If the type is str and the string
  1814. // data is already interned, then a qstr object is returned. Otherwise new memory is
  1815. // allocated for the object and the data is copied across.
  1816. mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
  1817. if (type == &mp_type_str) {
  1818. return mp_obj_new_str((const char*)data, len);
  1819. } else {
  1820. return mp_obj_new_bytes(data, len);
  1821. }
  1822. }
  1823. // Create a str using a qstr to store the data; may use existing or new qstr.
  1824. mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) {
  1825. return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
  1826. }
  1827. // Create a str/bytes object from the given vstr. The vstr buffer is resized to
  1828. // the exact length required and then reused for the str/bytes object. The vstr
  1829. // is cleared and can safely be passed to vstr_free if it was heap allocated.
  1830. mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
  1831. // if not a bytes object, look if a qstr with this data already exists
  1832. if (type == &mp_type_str) {
  1833. qstr q = qstr_find_strn(vstr->buf, vstr->len);
  1834. if (q != MP_QSTR_NULL) {
  1835. vstr_clear(vstr);
  1836. vstr->alloc = 0;
  1837. return MP_OBJ_NEW_QSTR(q);
  1838. }
  1839. }
  1840. // make a new str/bytes object
  1841. mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
  1842. o->base.type = type;
  1843. o->len = vstr->len;
  1844. o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
  1845. if (vstr->len + 1 == vstr->alloc) {
  1846. o->data = (byte*)vstr->buf;
  1847. } else {
  1848. o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
  1849. }
  1850. ((byte*)o->data)[o->len] = '\0'; // add null byte
  1851. vstr->buf = NULL;
  1852. vstr->alloc = 0;
  1853. return MP_OBJ_FROM_PTR(o);
  1854. }
  1855. mp_obj_t mp_obj_new_str(const char* data, size_t len) {
  1856. qstr q = qstr_find_strn(data, len);
  1857. if (q != MP_QSTR_NULL) {
  1858. // qstr with this data already exists
  1859. return MP_OBJ_NEW_QSTR(q);
  1860. } else {
  1861. // no existing qstr, don't make one
  1862. return mp_obj_new_str_copy(&mp_type_str, (const byte*)data, len);
  1863. }
  1864. }
  1865. mp_obj_t mp_obj_str_intern(mp_obj_t str) {
  1866. GET_STR_DATA_LEN(str, data, len);
  1867. return mp_obj_new_str_via_qstr((const char*)data, len);
  1868. }
  1869. mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) {
  1870. size_t len;
  1871. const char *data = mp_obj_str_get_data(obj, &len);
  1872. return mp_obj_new_str_via_qstr((const char*)data, len);
  1873. }
  1874. mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
  1875. return mp_obj_new_str_copy(&mp_type_bytes, data, len);
  1876. }
  1877. bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
  1878. if (mp_obj_is_qstr(s1) && mp_obj_is_qstr(s2)) {
  1879. return s1 == s2;
  1880. } else {
  1881. GET_STR_HASH(s1, h1);
  1882. GET_STR_HASH(s2, h2);
  1883. // If any of hashes is 0, it means it's not valid
  1884. if (h1 != 0 && h2 != 0 && h1 != h2) {
  1885. return false;
  1886. }
  1887. GET_STR_DATA_LEN(s1, d1, l1);
  1888. GET_STR_DATA_LEN(s2, d2, l2);
  1889. if (l1 != l2) {
  1890. return false;
  1891. }
  1892. return memcmp(d1, d2, l1) == 0;
  1893. }
  1894. }
  1895. STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) {
  1896. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1897. mp_raise_TypeError("can't convert to str implicitly");
  1898. } else {
  1899. const qstr src_name = mp_obj_get_type(self_in)->name;
  1900. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  1901. "can't convert '%q' object to %q implicitly",
  1902. src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
  1903. }
  1904. }
  1905. // use this if you will anyway convert the string to a qstr
  1906. // will be more efficient for the case where it's already a qstr
  1907. qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
  1908. if (mp_obj_is_qstr(self_in)) {
  1909. return MP_OBJ_QSTR_VALUE(self_in);
  1910. } else if (mp_obj_is_type(self_in, &mp_type_str)) {
  1911. mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
  1912. return qstr_from_strn((char*)self->data, self->len);
  1913. } else {
  1914. bad_implicit_conversion(self_in);
  1915. }
  1916. }
  1917. // only use this function if you need the str data to be zero terminated
  1918. // at the moment all strings are zero terminated to help with C ASCIIZ compatibility
  1919. const char *mp_obj_str_get_str(mp_obj_t self_in) {
  1920. if (mp_obj_is_str_or_bytes(self_in)) {
  1921. GET_STR_DATA_LEN(self_in, s, l);
  1922. (void)l; // len unused
  1923. return (const char*)s;
  1924. } else {
  1925. bad_implicit_conversion(self_in);
  1926. }
  1927. }
  1928. const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
  1929. if (mp_obj_is_str_or_bytes(self_in)) {
  1930. GET_STR_DATA_LEN(self_in, s, l);
  1931. *len = l;
  1932. return (const char*)s;
  1933. } else {
  1934. bad_implicit_conversion(self_in);
  1935. }
  1936. }
  1937. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
  1938. const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
  1939. if (mp_obj_is_qstr(self_in)) {
  1940. return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
  1941. } else {
  1942. *len = ((mp_obj_str_t*)self_in)->len;
  1943. return ((mp_obj_str_t*)self_in)->data;
  1944. }
  1945. }
  1946. #endif
  1947. /******************************************************************************/
  1948. /* str iterator */
  1949. typedef struct _mp_obj_str8_it_t {
  1950. mp_obj_base_t base;
  1951. mp_fun_1_t iternext;
  1952. mp_obj_t str;
  1953. size_t cur;
  1954. } mp_obj_str8_it_t;
  1955. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  1956. STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
  1957. mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
  1958. GET_STR_DATA_LEN(self->str, str, len);
  1959. if (self->cur < len) {
  1960. mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1);
  1961. self->cur += 1;
  1962. return o_out;
  1963. } else {
  1964. return MP_OBJ_STOP_ITERATION;
  1965. }
  1966. }
  1967. STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
  1968. assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
  1969. mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
  1970. o->base.type = &mp_type_polymorph_iter;
  1971. o->iternext = str_it_iternext;
  1972. o->str = str;
  1973. o->cur = 0;
  1974. return MP_OBJ_FROM_PTR(o);
  1975. }
  1976. #endif
  1977. STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
  1978. mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
  1979. GET_STR_DATA_LEN(self->str, str, len);
  1980. if (self->cur < len) {
  1981. mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
  1982. self->cur += 1;
  1983. return o_out;
  1984. } else {
  1985. return MP_OBJ_STOP_ITERATION;
  1986. }
  1987. }
  1988. mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
  1989. assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
  1990. mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
  1991. o->base.type = &mp_type_polymorph_iter;
  1992. o->iternext = bytes_it_iternext;
  1993. o->str = str;
  1994. o->cur = 0;
  1995. return MP_OBJ_FROM_PTR(o);
  1996. }