objstr.c 75 KB

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