objstr.c 76 KB

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