objstr.c 75 KB

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