objstr.c 77 KB

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