objstr.c 75 KB

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