strconv.odin 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. package strconv
  2. import "core:unicode/utf8"
  3. import "decimal"
  4. /*
  5. Parses a boolean value from the input string
  6. **Inputs**
  7. - s: The input string
  8. - true: "1", "t", "T", "true", "TRUE", "True"
  9. - false: "0", "f", "F", "false", "FALSE", "False"
  10. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  11. **Returns**
  12. - result: The parsed boolean value (default: false)
  13. - ok: A boolean indicating whether the parsing was successful
  14. */
  15. parse_bool :: proc(s: string, n: ^int = nil) -> (result: bool = false, ok: bool) {
  16. switch s {
  17. case "1", "t", "T", "true", "TRUE", "True":
  18. if n != nil { n^ = len(s) }
  19. return true, true
  20. case "0", "f", "F", "false", "FALSE", "False":
  21. if n != nil { n^ = len(s) }
  22. return false, true
  23. }
  24. return
  25. }
  26. /*
  27. Finds the integer value of the given rune
  28. **Inputs**
  29. - r: The input rune to find the integer value of
  30. **Returns** The integer value of the given rune
  31. */
  32. _digit_value :: proc(r: rune) -> int {
  33. ri := int(r)
  34. v: int = 16
  35. switch r {
  36. case '0'..='9': v = ri-'0'
  37. case 'a'..='z': v = ri-'a'+10
  38. case 'A'..='Z': v = ri-'A'+10
  39. }
  40. return v
  41. }
  42. /*
  43. Parses an integer value from the input string in the given base, without a prefix
  44. **Inputs**
  45. - str: The input string to parse the integer value from
  46. - base: The base of the integer value to be parsed (must be between 1 and 16)
  47. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  48. Example:
  49. import "core:fmt"
  50. import "core:strconv"
  51. parse_i64_of_base_example :: proc() {
  52. n, ok := strconv.parse_i64_of_base("-1234e3", 10)
  53. fmt.println(n, ok)
  54. }
  55. Output:
  56. -1234 false
  57. **Returns**
  58. - value: Parses an integer value from a string, in the given base, without a prefix.
  59. - ok: ok=false if no numeric value of the appropriate base could be found, or if the input string contained more than just the number.
  60. */
  61. parse_i64_of_base :: proc(str: string, base: int, n: ^int = nil) -> (value: i64, ok: bool) {
  62. assert(base <= 16, "base must be 1-16")
  63. s := str
  64. defer if n != nil { n^ = len(str)-len(s) }
  65. if s == "" {
  66. return
  67. }
  68. neg := false
  69. if len(s) > 1 {
  70. switch s[0] {
  71. case '-':
  72. neg = true
  73. s = s[1:]
  74. case '+':
  75. s = s[1:]
  76. }
  77. }
  78. i := 0
  79. for r in s {
  80. if r == '_' {
  81. i += 1
  82. continue
  83. }
  84. v := i64(_digit_value(r))
  85. if v >= i64(base) {
  86. break
  87. }
  88. value *= i64(base)
  89. value += v
  90. i += 1
  91. }
  92. s = s[i:]
  93. if neg {
  94. value = -value
  95. }
  96. ok = len(s) == 0
  97. return
  98. }
  99. /*
  100. Parses an integer value from the input string in base 10, unless there's a prefix
  101. **Inputs**
  102. - str: The input string to parse the integer value from
  103. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  104. Example:
  105. import "core:fmt"
  106. import "core:strconv"
  107. parse_i64_maybe_prefixed_example :: proc() {
  108. n, ok := strconv.parse_i64_maybe_prefixed("1234")
  109. fmt.println(n,ok)
  110. n, ok = strconv.parse_i64_maybe_prefixed("0xeeee")
  111. fmt.println(n,ok)
  112. }
  113. Output:
  114. 1234 true
  115. 61166 true
  116. **Returns**
  117. - value: The parsed integer value
  118. - ok: ok=false if a valid integer could not be found, or if the input string contained more than just the number.
  119. */
  120. parse_i64_maybe_prefixed :: proc(str: string, n: ^int = nil) -> (value: i64, ok: bool) {
  121. s := str
  122. defer if n != nil { n^ = len(str)-len(s) }
  123. if s == "" {
  124. return
  125. }
  126. neg := false
  127. if len(s) > 1 {
  128. switch s[0] {
  129. case '-':
  130. neg = true
  131. s = s[1:]
  132. case '+':
  133. s = s[1:]
  134. }
  135. }
  136. base: i64 = 10
  137. if len(s) > 2 && s[0] == '0' {
  138. switch s[1] {
  139. case 'b': base = 2; s = s[2:]
  140. case 'o': base = 8; s = s[2:]
  141. case 'd': base = 10; s = s[2:]
  142. case 'z': base = 12; s = s[2:]
  143. case 'x': base = 16; s = s[2:]
  144. }
  145. }
  146. i := 0
  147. for r in s {
  148. if r == '_' {
  149. i += 1
  150. continue
  151. }
  152. v := i64(_digit_value(r))
  153. if v >= base {
  154. break
  155. }
  156. value *= base
  157. value += v
  158. i += 1
  159. }
  160. s = s[i:]
  161. if neg {
  162. value = -value
  163. }
  164. ok = len(s) == 0
  165. return
  166. }
  167. //
  168. parse_i64 :: proc{parse_i64_maybe_prefixed, parse_i64_of_base}
  169. /*
  170. Parses an unsigned 64-bit integer value from the input string without a prefix, using the specified base
  171. **Inputs**
  172. - str: The input string to parse
  173. - base: The base of the number system to use for parsing
  174. - Must be between 1 and 16 (inclusive)
  175. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  176. Example:
  177. import "core:fmt"
  178. import "core:strconv"
  179. parse_u64_of_base_example :: proc() {
  180. n, ok := strconv.parse_u64_of_base("1234e3", 10)
  181. fmt.println(n,ok)
  182. n, ok = strconv.parse_u64_of_base("5678eee",16)
  183. fmt.println(n,ok)
  184. }
  185. Output:
  186. 1234 false
  187. 90672878 true
  188. **Returns**
  189. - value: The parsed uint64 value
  190. - ok: A boolean indicating whether the parsing was successful
  191. */
  192. parse_u64_of_base :: proc(str: string, base: int, n: ^int = nil) -> (value: u64, ok: bool) {
  193. assert(base <= 16, "base must be 1-16")
  194. s := str
  195. defer if n != nil { n^ = len(str)-len(s) }
  196. if s == "" {
  197. return
  198. }
  199. if len(s) > 1 && s[0] == '+' {
  200. s = s[1:]
  201. }
  202. i := 0
  203. for r in s {
  204. if r == '_' {
  205. i += 1
  206. continue
  207. }
  208. v := u64(_digit_value(r))
  209. if v >= u64(base) {
  210. break
  211. }
  212. value *= u64(base)
  213. value += v
  214. i += 1
  215. }
  216. s = s[i:]
  217. ok = len(s) == 0
  218. return
  219. }
  220. /*
  221. Parses an unsigned 64-bit integer value from the input string, using the specified base or inferring the base from a prefix
  222. **Inputs**
  223. - str: The input string to parse
  224. - base: The base of the number system to use for parsing (default: 0)
  225. - If base is 0, it will be inferred based on the prefix in the input string (e.g. '0x' for hexadecimal)
  226. - If base is not 0, it will be used for parsing regardless of any prefix in the input string
  227. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  228. Example:
  229. import "core:fmt"
  230. import "core:strconv"
  231. parse_u64_maybe_prefixed_example :: proc() {
  232. n, ok := strconv.parse_u64_maybe_prefixed("1234")
  233. fmt.println(n,ok)
  234. n, ok = strconv.parse_u64_maybe_prefixed("0xee")
  235. fmt.println(n,ok)
  236. }
  237. Output:
  238. 1234 true
  239. 238 true
  240. **Returns**
  241. - value: The parsed uint64 value
  242. - ok: ok=false if a valid integer could not be found, if the value was negative, or if the input string contained more than just the number.
  243. */
  244. parse_u64_maybe_prefixed :: proc(str: string, n: ^int = nil) -> (value: u64, ok: bool) {
  245. s := str
  246. defer if n != nil { n^ = len(str)-len(s) }
  247. if s == "" {
  248. return
  249. }
  250. if len(s) > 1 && s[0] == '+' {
  251. s = s[1:]
  252. }
  253. base := u64(10)
  254. if len(s) > 2 && s[0] == '0' {
  255. switch s[1] {
  256. case 'b': base = 2; s = s[2:]
  257. case 'o': base = 8; s = s[2:]
  258. case 'd': base = 10; s = s[2:]
  259. case 'z': base = 12; s = s[2:]
  260. case 'x': base = 16; s = s[2:]
  261. }
  262. }
  263. i := 0
  264. for r in s {
  265. if r == '_' {
  266. i += 1
  267. continue
  268. }
  269. v := u64(_digit_value(r))
  270. if v >= base {
  271. break
  272. }
  273. value *= base
  274. value += v
  275. i += 1
  276. }
  277. s = s[i:]
  278. ok = len(s) == 0
  279. return
  280. }
  281. //
  282. parse_u64 :: proc{parse_u64_maybe_prefixed, parse_u64_of_base}
  283. /*
  284. Parses a signed integer value from the input string, using the specified base or inferring the base from a prefix
  285. **Inputs**
  286. - s: The input string to parse
  287. - base: The base of the number system to use for parsing (default: 0)
  288. - If base is 0, it will be inferred based on the prefix in the input string (e.g. '0x' for hexadecimal)
  289. - If base is not 0, it will be used for parsing regardless of any prefix in the input string
  290. Example:
  291. import "core:fmt"
  292. import "core:strconv"
  293. parse_int_example :: proc() {
  294. n, ok := strconv.parse_int("1234") // without prefix, inferred base 10
  295. fmt.println(n,ok)
  296. n, ok = strconv.parse_int("ffff", 16) // without prefix, explicit base
  297. fmt.println(n,ok)
  298. n, ok = strconv.parse_int("0xffff") // with prefix and inferred base
  299. fmt.println(n,ok)
  300. }
  301. Output:
  302. 1234 true
  303. 65535 true
  304. 65535 true
  305. **Returns**
  306. - value: The parsed int value
  307. - ok: `false` if no appropriate value could be found, or if the input string contained more than just the number.
  308. */
  309. parse_int :: proc(s: string, base := 0, n: ^int = nil) -> (value: int, ok: bool) {
  310. v: i64 = ---
  311. switch base {
  312. case 0: v, ok = parse_i64_maybe_prefixed(s, n)
  313. case: v, ok = parse_i64_of_base(s, base, n)
  314. }
  315. value = int(v)
  316. return
  317. }
  318. /*
  319. Parses an unsigned integer value from the input string, using the specified base or inferring the base from a prefix
  320. **Inputs**
  321. - s: The input string to parse
  322. - base: The base of the number system to use for parsing (default: 0, inferred)
  323. - If base is 0, it will be inferred based on the prefix in the input string (e.g. '0x' for hexadecimal)
  324. - If base is not 0, it will be used for parsing regardless of any prefix in the input string
  325. Example:
  326. import "core:fmt"
  327. import "core:strconv"
  328. parse_uint_example :: proc() {
  329. n, ok := strconv.parse_uint("1234") // without prefix, inferred base 10
  330. fmt.println(n,ok)
  331. n, ok = strconv.parse_uint("ffff", 16) // without prefix, explicit base
  332. fmt.println(n,ok)
  333. n, ok = strconv.parse_uint("0xffff") // with prefix and inferred base
  334. fmt.println(n,ok)
  335. }
  336. Output:
  337. 1234 true
  338. 65535 true
  339. 65535 true
  340. **Returns**
  341. value: The parsed uint value
  342. ok: `false` if no appropriate value could be found; the value was negative; he input string contained more than just the number
  343. */
  344. parse_uint :: proc(s: string, base := 0, n: ^int = nil) -> (value: uint, ok: bool) {
  345. v: u64 = ---
  346. switch base {
  347. case 0: v, ok = parse_u64_maybe_prefixed(s, n)
  348. case: v, ok = parse_u64_of_base(s, base, n)
  349. }
  350. value = uint(v)
  351. return
  352. }
  353. /*
  354. Parses an integer value from a string in the given base, without any prefix
  355. **Inputs**
  356. - str: The input string containing the integer value
  357. - base: The base (radix) to use for parsing the integer (1-16)
  358. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  359. Example:
  360. import "core:fmt"
  361. import "core:strconv"
  362. parse_i128_of_base_example :: proc() {
  363. n, ok := strconv.parse_i128_of_base("-1234eeee", 10)
  364. fmt.println(n,ok)
  365. }
  366. Output:
  367. -1234 false
  368. **Returns**
  369. - value: The parsed i128 value
  370. - ok: false if no numeric value of the appropriate base could be found, or if the input string contained more than just the number.
  371. */
  372. parse_i128_of_base :: proc(str: string, base: int, n: ^int = nil) -> (value: i128, ok: bool) {
  373. assert(base <= 16, "base must be 1-16")
  374. s := str
  375. defer if n != nil { n^ = len(str)-len(s) }
  376. if s == "" {
  377. return
  378. }
  379. neg := false
  380. if len(s) > 1 {
  381. switch s[0] {
  382. case '-':
  383. neg = true
  384. s = s[1:]
  385. case '+':
  386. s = s[1:]
  387. }
  388. }
  389. i := 0
  390. for r in s {
  391. if r == '_' {
  392. i += 1
  393. continue
  394. }
  395. v := i128(_digit_value(r))
  396. if v >= i128(base) {
  397. break
  398. }
  399. value *= i128(base)
  400. value += v
  401. i += 1
  402. }
  403. s = s[i:]
  404. if neg {
  405. value = -value
  406. }
  407. ok = len(s) == 0
  408. return
  409. }
  410. /*
  411. Parses an integer value from a string in base 10, unless there's a prefix
  412. **Inputs**
  413. - str: The input string containing the integer value
  414. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  415. Example:
  416. import "core:fmt"
  417. import "core:strconv"
  418. parse_i128_maybe_prefixed_example :: proc() {
  419. n, ok := strconv.parse_i128_maybe_prefixed("1234")
  420. fmt.println(n, ok)
  421. n, ok = strconv.parse_i128_maybe_prefixed("0xeeee")
  422. fmt.println(n, ok)
  423. }
  424. Output:
  425. 1234 true
  426. 61166 true
  427. **Returns**
  428. - value: The parsed i128 value
  429. - ok: `false` if a valid integer could not be found, or if the input string contained more than just the number.
  430. */
  431. parse_i128_maybe_prefixed :: proc(str: string, n: ^int = nil) -> (value: i128, ok: bool) {
  432. s := str
  433. defer if n != nil { n^ = len(str)-len(s) }
  434. if s == "" {
  435. return
  436. }
  437. neg := false
  438. if len(s) > 1 {
  439. switch s[0] {
  440. case '-':
  441. neg = true
  442. s = s[1:]
  443. case '+':
  444. s = s[1:]
  445. }
  446. }
  447. base: i128 = 10
  448. if len(s) > 2 && s[0] == '0' {
  449. switch s[1] {
  450. case 'b': base = 2; s = s[2:]
  451. case 'o': base = 8; s = s[2:]
  452. case 'd': base = 10; s = s[2:]
  453. case 'z': base = 12; s = s[2:]
  454. case 'x': base = 16; s = s[2:]
  455. }
  456. }
  457. i := 0
  458. for r in s {
  459. if r == '_' {
  460. i += 1
  461. continue
  462. }
  463. v := i128(_digit_value(r))
  464. if v >= base {
  465. break
  466. }
  467. value *= base
  468. value += v
  469. i += 1
  470. }
  471. s = s[i:]
  472. if neg {
  473. value = -value
  474. }
  475. ok = len(s) == 0
  476. return
  477. }
  478. //
  479. parse_i128 :: proc{parse_i128_maybe_prefixed, parse_i128_of_base}
  480. /*
  481. Parses an unsigned integer value from a string in the given base, without any prefix
  482. **Inputs**
  483. - str: The input string containing the integer value
  484. - base: The base (radix) to use for parsing the integer (1-16)
  485. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  486. Example:
  487. import "core:fmt"
  488. import "core:strconv"
  489. parse_u128_of_base_example :: proc() {
  490. n, ok := strconv.parse_u128_of_base("1234eeee", 10)
  491. fmt.println(n, ok)
  492. n, ok = strconv.parse_u128_of_base("5678eeee", 16)
  493. fmt.println(n, ok)
  494. }
  495. Output:
  496. 1234 false
  497. 1450766062 true
  498. **Returns**
  499. - value: The parsed u128 value
  500. - ok: `false` if no numeric value of the appropriate base could be found, or if the input string contained more than just the number.
  501. */
  502. parse_u128_of_base :: proc(str: string, base: int, n: ^int = nil) -> (value: u128, ok: bool) {
  503. assert(base <= 16, "base must be 1-16")
  504. s := str
  505. defer if n != nil { n^ = len(str)-len(s) }
  506. if s == "" {
  507. return
  508. }
  509. if len(s) > 1 && s[0] == '+' {
  510. s = s[1:]
  511. }
  512. i := 0
  513. for r in s {
  514. if r == '_' {
  515. i += 1
  516. continue
  517. }
  518. v := u128(_digit_value(r))
  519. if v >= u128(base) {
  520. break
  521. }
  522. value *= u128(base)
  523. value += v
  524. i += 1
  525. }
  526. s = s[i:]
  527. ok = len(s) == 0
  528. return
  529. }
  530. /*
  531. Parses an unsigned integer value from a string in base 10, unless there's a prefix
  532. **Inputs**
  533. - str: The input string containing the integer value
  534. - n: An optional pointer to an int to store the length of the parsed substring (default: nil)
  535. Example:
  536. import "core:fmt"
  537. import "core:strconv"
  538. parse_u128_maybe_prefixed_example :: proc() {
  539. n, ok := strconv.parse_u128_maybe_prefixed("1234")
  540. fmt.println(n, ok)
  541. n, ok = strconv.parse_u128_maybe_prefixed("5678eeee")
  542. fmt.println(n, ok)
  543. }
  544. Output:
  545. 1234 true
  546. 5678 false
  547. **Returns**
  548. - value: The parsed u128 value
  549. - ok: false if a valid integer could not be found, if the value was negative, or if the input string contained more than just the number.
  550. */
  551. parse_u128_maybe_prefixed :: proc(str: string, n: ^int = nil) -> (value: u128, ok: bool) {
  552. s := str
  553. defer if n != nil { n^ = len(str)-len(s) }
  554. if s == "" {
  555. return
  556. }
  557. if len(s) > 1 && s[0] == '+' {
  558. s = s[1:]
  559. }
  560. base := u128(10)
  561. if len(s) > 2 && s[0] == '0' {
  562. switch s[1] {
  563. case 'b': base = 2; s = s[2:]
  564. case 'o': base = 8; s = s[2:]
  565. case 'd': base = 10; s = s[2:]
  566. case 'z': base = 12; s = s[2:]
  567. case 'x': base = 16; s = s[2:]
  568. }
  569. }
  570. i := 0
  571. for r in s {
  572. if r == '_' {
  573. i += 1
  574. continue
  575. }
  576. v := u128(_digit_value(r))
  577. if v >= base {
  578. break
  579. }
  580. value *= base
  581. value += v
  582. i += 1
  583. }
  584. s = s[i:]
  585. ok = len(s) == 0
  586. return
  587. }
  588. //
  589. parse_u128 :: proc{parse_u128_maybe_prefixed, parse_u128_of_base}
  590. /*
  591. Converts a byte to lowercase
  592. **Inputs**
  593. - ch: A byte character to be converted to lowercase.
  594. **Returns**
  595. - A lowercase byte character.
  596. */
  597. @(private)
  598. lower :: #force_inline proc "contextless" (ch: byte) -> byte { return ('a' - 'A') | ch }
  599. /*
  600. Parses a 32-bit floating point number from a string
  601. **Inputs**
  602. - s: The input string containing a 32-bit floating point number.
  603. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  604. Example:
  605. import "core:fmt"
  606. import "core:strconv"
  607. parse_f32_example :: proc() {
  608. n, ok := strconv.parse_f32("1234eee")
  609. fmt.printfln("%.3f %v", n, ok)
  610. n, ok = strconv.parse_f32("5678e2")
  611. fmt.printfln("%.3f %v", n, ok)
  612. }
  613. Output:
  614. 0.000 false
  615. 567800.000 true
  616. **Returns**
  617. - value: The parsed 32-bit floating point number.
  618. - ok: `false` if a base 10 float could not be found, or if the input string contained more than just the number.
  619. */
  620. parse_f32 :: proc(s: string, n: ^int = nil) -> (value: f32, ok: bool) {
  621. v: f64 = ---
  622. v, ok = parse_f64(s, n)
  623. return f32(v), ok
  624. }
  625. /*
  626. Parses a 64-bit floating point number from a string
  627. **Inputs**
  628. - str: The input string containing a 64-bit floating point number.
  629. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  630. Example:
  631. import "core:fmt"
  632. import "core:strconv"
  633. parse_f64_example :: proc() {
  634. n, ok := strconv.parse_f64("1234eee")
  635. fmt.printfln("%.3f %v", n, ok)
  636. n, ok = strconv.parse_f64("5678e2")
  637. fmt.printfln("%.3f %v", n, ok)
  638. }
  639. Output:
  640. 0.000 false
  641. 567800.000 true
  642. **Returns**
  643. - value: The parsed 64-bit floating point number.
  644. - ok: `false` if a base 10 float could not be found, or if the input string contained more than just the number.
  645. */
  646. parse_f64 :: proc(str: string, n: ^int = nil) -> (value: f64, ok: bool) {
  647. nr: int
  648. value, nr, ok = parse_f64_prefix(str)
  649. if ok && len(str) != nr {
  650. ok = false
  651. }
  652. if n != nil { n^ = nr }
  653. return
  654. }
  655. /*
  656. Parses a 32-bit floating point number from a string and returns the parsed number, the length of the parsed substring, and a boolean indicating whether the parsing was successful
  657. **Inputs**
  658. - str: The input string containing a 32-bit floating point number.
  659. Example:
  660. import "core:fmt"
  661. import "core:strconv"
  662. parse_f32_prefix_example :: proc() {
  663. n, _, ok := strconv.parse_f32_prefix("1234eee")
  664. fmt.printfln("%.3f %v", n, ok)
  665. n, _, ok = strconv.parse_f32_prefix("5678e2")
  666. fmt.printfln("%.3f %v", n, ok)
  667. }
  668. Output:
  669. 0.000 false
  670. 567800.000 true
  671. **Returns**
  672. - value: The parsed 32-bit floating point number.
  673. - nr: The length of the parsed substring.
  674. - ok: A boolean indicating whether the parsing was successful.
  675. */
  676. parse_f32_prefix :: proc(str: string) -> (value: f32, nr: int, ok: bool) {
  677. f: f64
  678. f, nr, ok = parse_f64_prefix(str)
  679. value = f32(f)
  680. return
  681. }
  682. /*
  683. Parses a 64-bit floating point number from a string and returns the parsed number, the length of the parsed substring, and a boolean indicating whether the parsing was successful
  684. **Inputs**
  685. - str: The input string containing a 64-bit floating point number.
  686. Example:
  687. import "core:fmt"
  688. import "core:strconv"
  689. parse_f64_prefix_example :: proc() {
  690. n, _, ok := strconv.parse_f64_prefix("12.34eee")
  691. fmt.printfln("%.3f %v", n, ok)
  692. n, _, ok = strconv.parse_f64_prefix("12.34e2")
  693. fmt.printfln("%.3f %v", n, ok)
  694. n, _, ok = strconv.parse_f64_prefix("13.37 hellope")
  695. fmt.printfln("%.3f %v", n, ok)
  696. }
  697. Output:
  698. 0.000 false
  699. 1234.000 true
  700. 13.370 true
  701. **Returns**
  702. - value: The parsed 64-bit floating point number.
  703. - nr: The length of the parsed substring.
  704. - ok: `false` if a base 10 float could not be found
  705. */
  706. parse_f64_prefix :: proc(str: string) -> (value: f64, nr: int, ok: bool) {
  707. common_prefix_len_ignore_case :: proc "contextless" (s, prefix: string) -> int {
  708. n := len(prefix)
  709. if n > len(s) {
  710. n = len(s)
  711. }
  712. for i in 0..<n {
  713. c := s[i]
  714. if 'A' <= c && c <= 'Z' {
  715. c += 'a' - 'A'
  716. }
  717. if c != prefix[i] {
  718. return i
  719. }
  720. }
  721. return n
  722. }
  723. check_special :: proc "contextless" (s: string) -> (f: f64, n: int, ok: bool) {
  724. s := s
  725. if len(s) > 0 {
  726. sign := 1
  727. nsign := 0
  728. switch s[0] {
  729. case '+', '-':
  730. if s[0] == '-' {
  731. sign = -1
  732. }
  733. nsign = 1
  734. s = s[1:]
  735. fallthrough
  736. case 'i', 'I':
  737. m := common_prefix_len_ignore_case(s, "infinity")
  738. if 3 <= m && m < 9 { // "inf" to "infinity"
  739. f = 0h7ff00000_00000000 if sign == 1 else 0hfff00000_00000000
  740. if m == 8 {
  741. // We only count the entire prefix if it is precisely "infinity".
  742. n = nsign + m
  743. } else {
  744. // The string was either only "inf" or incomplete.
  745. n = nsign + 3
  746. }
  747. ok = true
  748. return
  749. }
  750. case 'n', 'N':
  751. if common_prefix_len_ignore_case(s, "nan") == 3 {
  752. f = 0h7ff80000_00000001
  753. n = nsign + 3
  754. ok = true
  755. return
  756. }
  757. }
  758. }
  759. return
  760. }
  761. parse_components :: proc "contextless" (s: string) -> (mantissa: u64, exp: int, neg, trunc, hex: bool, i: int, ok: bool) {
  762. if len(s) == 0 {
  763. return
  764. }
  765. switch s[i] {
  766. case '+': i += 1
  767. case '-': i += 1; neg = true
  768. }
  769. base := u64(10)
  770. MAX_MANT_DIGITS := 19
  771. exp_char := byte('e')
  772. // support stupid 0x1.ABp100 hex floats even if Odin doesn't
  773. if i+2 < len(s) && s[i] == '0' && lower(s[i+1]) == 'x' {
  774. base = 16
  775. MAX_MANT_DIGITS = 16
  776. i += 2
  777. exp_char = 'p'
  778. hex = true
  779. }
  780. underscores := false
  781. saw_dot, saw_digits := false, false
  782. nd := 0
  783. nd_mant := 0
  784. decimal_point := 0
  785. trailing_zeroes_nd := -1
  786. loop: for ; i < len(s); i += 1 {
  787. switch c := s[i]; true {
  788. case c == '_':
  789. underscores = true
  790. continue loop
  791. case c == '.':
  792. if saw_dot {
  793. break loop
  794. }
  795. saw_dot = true
  796. decimal_point = nd
  797. continue loop
  798. case '0' <= c && c <= '9':
  799. saw_digits = true
  800. if c == '0' {
  801. if nd == 0 {
  802. decimal_point -= 1
  803. continue loop
  804. }
  805. if trailing_zeroes_nd == -1 {
  806. trailing_zeroes_nd = nd
  807. }
  808. } else {
  809. trailing_zeroes_nd = -1
  810. }
  811. nd += 1
  812. if nd_mant < MAX_MANT_DIGITS {
  813. mantissa *= base
  814. mantissa += u64(c - '0')
  815. nd_mant += 1
  816. } else if c != '0' {
  817. trunc = true
  818. }
  819. continue loop
  820. case base == 16 && 'a' <= lower(c) && lower(c) <= 'f':
  821. saw_digits = true
  822. nd += 1
  823. if nd_mant < MAX_MANT_DIGITS {
  824. mantissa *= 16
  825. mantissa += u64(lower(c) - 'a' + 10)
  826. nd_mant += 1
  827. } else {
  828. trunc = true
  829. }
  830. continue loop
  831. }
  832. break loop
  833. }
  834. if !saw_digits {
  835. return
  836. }
  837. if !saw_dot {
  838. decimal_point = nd
  839. }
  840. if trailing_zeroes_nd > 0 {
  841. trailing_zeroes_nd = nd_mant - trailing_zeroes_nd
  842. }
  843. for /**/; trailing_zeroes_nd > 0; trailing_zeroes_nd -= 1 {
  844. mantissa /= base
  845. nd_mant -= 1
  846. nd -= 1
  847. }
  848. if base == 16 {
  849. decimal_point *= 4
  850. nd_mant *= 4
  851. }
  852. if i < len(s) && lower(s[i]) == exp_char {
  853. i += 1
  854. if i >= len(s) { return }
  855. exp_sign := 1
  856. switch s[i] {
  857. case '+': i += 1
  858. case '-': i += 1; exp_sign = -1
  859. }
  860. if i >= len(s) || s[i] < '0' || s[i] > '9' {
  861. return
  862. }
  863. e := 0
  864. for ; i < len(s) && ('0' <= s[i] && s[i] <= '9' || s[i] == '_'); i += 1 {
  865. if s[i] == '_' {
  866. underscores = true
  867. continue
  868. }
  869. if e < 1e5 {
  870. e = e*10 + int(s[i]) - '0'
  871. }
  872. }
  873. decimal_point += e * exp_sign
  874. } else if base == 16 {
  875. return
  876. }
  877. if mantissa != 0 {
  878. exp = decimal_point - nd_mant
  879. }
  880. ok = true
  881. return
  882. }
  883. parse_hex :: proc "contextless" (s: string, mantissa: u64, exp: int, neg, trunc: bool) -> (f64, bool) {
  884. info := &_f64_info
  885. mantissa, exp := mantissa, exp
  886. MAX_EXP := 1<<info.expbits + info.bias - 2
  887. MIN_EXP := info.bias + 1
  888. exp += int(info.mantbits)
  889. for mantissa != 0 && mantissa >> (info.mantbits+2) == 0 {
  890. mantissa <<= 1
  891. exp -= 1
  892. }
  893. if trunc {
  894. mantissa |= 1
  895. }
  896. for mantissa != 0 && mantissa >> (info.mantbits+2) == 0 {
  897. mantissa = mantissa>>1 | mantissa&1
  898. exp += 1
  899. }
  900. // denormalize
  901. if mantissa > 1 && exp < MIN_EXP-2 {
  902. mantissa = mantissa>>1 | mantissa&1
  903. exp += 1
  904. }
  905. round := mantissa & 3
  906. mantissa >>= 2
  907. round |= mantissa & 1 // round to even
  908. exp += 2
  909. if round == 3 {
  910. mantissa += 1
  911. if mantissa == 1 << (1 + info.mantbits) {
  912. mantissa >>= 1
  913. exp += 1
  914. }
  915. }
  916. if mantissa>>info.mantbits == 0 {
  917. // zero or denormal
  918. exp = info.bias
  919. }
  920. ok := true
  921. if exp > MAX_EXP {
  922. // infinity or invalid
  923. mantissa = 1<<info.mantbits
  924. exp = MAX_EXP + 1
  925. ok = false
  926. }
  927. bits := mantissa & (1<<info.mantbits - 1)
  928. bits |= u64((exp-info.bias) & (1<<info.expbits - 1)) << info.mantbits
  929. if neg {
  930. bits |= 1 << info.mantbits << info.expbits
  931. }
  932. return transmute(f64)bits, ok
  933. }
  934. if value, nr, ok = check_special(str); ok {
  935. return
  936. }
  937. mantissa: u64
  938. exp: int
  939. neg, trunc, hex: bool
  940. mantissa, exp, neg, trunc, hex, nr = parse_components(str) or_return
  941. if hex {
  942. value, ok = parse_hex(str, mantissa, exp, neg, trunc)
  943. return
  944. }
  945. trunc_block: if !trunc {
  946. @(static, rodata) pow10 := [?]f64{
  947. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  948. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  949. 1e20, 1e21, 1e22,
  950. }
  951. if mantissa>>_f64_info.mantbits != 0 {
  952. break trunc_block
  953. }
  954. f := f64(mantissa)
  955. f_abs := f
  956. if neg {
  957. f = -f
  958. }
  959. switch {
  960. case exp == 0:
  961. return f, nr, true
  962. case exp > 0 && exp <= 15+22:
  963. if exp > 22 {
  964. f *= pow10[exp-22]
  965. exp = 22
  966. }
  967. if f_abs > 1e15 || f_abs < 1e-15 {
  968. break trunc_block
  969. }
  970. return f * pow10[exp], nr, true
  971. case -22 <= exp && exp < 0:
  972. return f / pow10[-exp], nr, true
  973. }
  974. }
  975. d: decimal.Decimal
  976. decimal.set(&d, str[:nr])
  977. b, overflow := decimal_to_float_bits(&d, &_f64_info)
  978. value = transmute(f64)b
  979. ok = !overflow
  980. return
  981. }
  982. /*
  983. Parses a 128-bit complex number from a string
  984. **Inputs**
  985. - str: The input string containing a 128-bit complex number.
  986. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  987. Example:
  988. import "core:fmt"
  989. import "core:strconv"
  990. parse_complex128_example :: proc() {
  991. n: int
  992. c, ok := strconv.parse_complex128("3+1i", &n)
  993. fmt.printfln("%v %i %t", c, n, ok)
  994. c, ok = strconv.parse_complex128("5+7i hellope", &n)
  995. fmt.printfln("%v %i %t", c, n, ok)
  996. }
  997. Output:
  998. 3+1i 4 true
  999. 5+7i 4 false
  1000. **Returns**
  1001. - value: The parsed 128-bit complex number.
  1002. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1003. */
  1004. parse_complex128 :: proc(str: string, n: ^int = nil) -> (value: complex128, ok: bool) {
  1005. real_value, imag_value: f64
  1006. nr_r, nr_i: int
  1007. real_value, nr_r, _ = parse_f64_prefix(str)
  1008. imag_value, nr_i, _ = parse_f64_prefix(str[nr_r:])
  1009. i_parsed := len(str) >= nr_r + nr_i + 1 && str[nr_r + nr_i] == 'i'
  1010. if !i_parsed {
  1011. // No `i` means we refuse to treat the second float we parsed as an
  1012. // imaginary value.
  1013. imag_value = 0
  1014. nr_i = 0
  1015. }
  1016. ok = i_parsed && len(str) == nr_r + nr_i + 1
  1017. if n != nil {
  1018. n^ = nr_r + nr_i + (1 if i_parsed else 0)
  1019. }
  1020. value = complex(real_value, imag_value)
  1021. return
  1022. }
  1023. /*
  1024. Parses a 64-bit complex number from a string
  1025. **Inputs**
  1026. - str: The input string containing a 64-bit complex number.
  1027. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1028. Example:
  1029. import "core:fmt"
  1030. import "core:strconv"
  1031. parse_complex64_example :: proc() {
  1032. n: int
  1033. c, ok := strconv.parse_complex64("3+1i", &n)
  1034. fmt.printfln("%v %i %t", c, n, ok)
  1035. c, ok = strconv.parse_complex64("5+7i hellope", &n)
  1036. fmt.printfln("%v %i %t", c, n, ok)
  1037. }
  1038. Output:
  1039. 3+1i 4 true
  1040. 5+7i 4 false
  1041. **Returns**
  1042. - value: The parsed 64-bit complex number.
  1043. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1044. */
  1045. parse_complex64 :: proc(str: string, n: ^int = nil) -> (value: complex64, ok: bool) {
  1046. v: complex128 = ---
  1047. v, ok = parse_complex128(str, n)
  1048. return cast(complex64)v, ok
  1049. }
  1050. /*
  1051. Parses a 32-bit complex number from a string
  1052. **Inputs**
  1053. - str: The input string containing a 32-bit complex number.
  1054. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1055. Example:
  1056. import "core:fmt"
  1057. import "core:strconv"
  1058. parse_complex32_example :: proc() {
  1059. n: int
  1060. c, ok := strconv.parse_complex32("3+1i", &n)
  1061. fmt.printfln("%v %i %t", c, n, ok)
  1062. c, ok = strconv.parse_complex32("5+7i hellope", &n)
  1063. fmt.printfln("%v %i %t", c, n, ok)
  1064. }
  1065. Output:
  1066. 3+1i 4 true
  1067. 5+7i 4 false
  1068. **Returns**
  1069. - value: The parsed 32-bit complex number.
  1070. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1071. */
  1072. parse_complex32 :: proc(str: string, n: ^int = nil) -> (value: complex32, ok: bool) {
  1073. v: complex128 = ---
  1074. v, ok = parse_complex128(str, n)
  1075. return cast(complex32)v, ok
  1076. }
  1077. /*
  1078. Parses a 256-bit quaternion from a string
  1079. **Inputs**
  1080. - str: The input string containing a 256-bit quaternion.
  1081. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1082. Example:
  1083. import "core:fmt"
  1084. import "core:strconv"
  1085. parse_quaternion256_example :: proc() {
  1086. n: int
  1087. q, ok := strconv.parse_quaternion256("1+2i+3j+4k", &n)
  1088. fmt.printfln("%v %i %t", q, n, ok)
  1089. q, ok = strconv.parse_quaternion256("1+2i+3j+4k hellope", &n)
  1090. fmt.printfln("%v %i %t", q, n, ok)
  1091. }
  1092. Output:
  1093. 1+2i+3j+4k 10 true
  1094. 1+2i+3j+4k 10 false
  1095. **Returns**
  1096. - value: The parsed 256-bit quaternion.
  1097. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1098. */
  1099. parse_quaternion256 :: proc(str: string, n: ^int = nil) -> (value: quaternion256, ok: bool) {
  1100. iterate_and_assign :: proc (iter: ^string, terminator: byte, nr_total: ^int, state: bool) -> (value: f64, ok: bool) {
  1101. if !state {
  1102. return
  1103. }
  1104. nr: int
  1105. value, nr, _ = parse_f64_prefix(iter^)
  1106. iter^ = iter[nr:]
  1107. if len(iter) > 0 && iter[0] == terminator {
  1108. iter^ = iter[1:]
  1109. nr_total^ += nr + 1
  1110. ok = true
  1111. } else {
  1112. value = 0
  1113. }
  1114. return
  1115. }
  1116. real_value, imag_value, jmag_value, kmag_value: f64
  1117. nr: int
  1118. real_value, nr, _ = parse_f64_prefix(str)
  1119. iter := str[nr:]
  1120. // Need to have parsed at least something in order to get started.
  1121. ok = nr > 0
  1122. // Quaternion parsing is done this way to honour the rest of the API with
  1123. // regards to partial parsing. Otherwise, we could error out early.
  1124. imag_value, ok = iterate_and_assign(&iter, 'i', &nr, ok)
  1125. jmag_value, ok = iterate_and_assign(&iter, 'j', &nr, ok)
  1126. kmag_value, ok = iterate_and_assign(&iter, 'k', &nr, ok)
  1127. if len(iter) != 0 {
  1128. ok = false
  1129. }
  1130. if n != nil {
  1131. n^ = nr
  1132. }
  1133. value = quaternion(
  1134. real = real_value,
  1135. imag = imag_value,
  1136. jmag = jmag_value,
  1137. kmag = kmag_value)
  1138. return
  1139. }
  1140. /*
  1141. Parses a 128-bit quaternion from a string
  1142. **Inputs**
  1143. - str: The input string containing a 128-bit quaternion.
  1144. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1145. Example:
  1146. import "core:fmt"
  1147. import "core:strconv"
  1148. parse_quaternion128_example :: proc() {
  1149. n: int
  1150. q, ok := strconv.parse_quaternion128("1+2i+3j+4k", &n)
  1151. fmt.printfln("%v %i %t", q, n, ok)
  1152. q, ok = strconv.parse_quaternion128("1+2i+3j+4k hellope", &n)
  1153. fmt.printfln("%v %i %t", q, n, ok)
  1154. }
  1155. Output:
  1156. 1+2i+3j+4k 10 true
  1157. 1+2i+3j+4k 10 false
  1158. **Returns**
  1159. - value: The parsed 128-bit quaternion.
  1160. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1161. */
  1162. parse_quaternion128 :: proc(str: string, n: ^int = nil) -> (value: quaternion128, ok: bool) {
  1163. v: quaternion256 = ---
  1164. v, ok = parse_quaternion256(str, n)
  1165. return cast(quaternion128)v, ok
  1166. }
  1167. /*
  1168. Parses a 64-bit quaternion from a string
  1169. **Inputs**
  1170. - str: The input string containing a 64-bit quaternion.
  1171. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1172. Example:
  1173. import "core:fmt"
  1174. import "core:strconv"
  1175. parse_quaternion64_example :: proc() {
  1176. n: int
  1177. q, ok := strconv.parse_quaternion64("1+2i+3j+4k", &n)
  1178. fmt.printfln("%v %i %t", q, n, ok)
  1179. q, ok = strconv.parse_quaternion64("1+2i+3j+4k hellope", &n)
  1180. fmt.printfln("%v %i %t", q, n, ok)
  1181. }
  1182. Output:
  1183. 1+2i+3j+4k 10 true
  1184. 1+2i+3j+4k 10 false
  1185. **Returns**
  1186. - value: The parsed 64-bit quaternion.
  1187. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1188. */
  1189. parse_quaternion64 :: proc(str: string, n: ^int = nil) -> (value: quaternion64, ok: bool) {
  1190. v: quaternion256 = ---
  1191. v, ok = parse_quaternion256(str, n)
  1192. return cast(quaternion64)v, ok
  1193. }
  1194. /*
  1195. Appends a boolean value as a string to the given buffer
  1196. **Inputs**
  1197. - buf: The buffer to append the boolean value to
  1198. - b: The boolean value to be appended
  1199. Example:
  1200. import "core:fmt"
  1201. import "core:strconv"
  1202. append_bool_example :: proc() {
  1203. buf: [6]byte
  1204. result := strconv.append_bool(buf[:], true)
  1205. fmt.println(result, buf)
  1206. }
  1207. Output:
  1208. true [116, 114, 117, 101, 0, 0]
  1209. **Returns**
  1210. - The resulting string after appending the boolean value
  1211. */
  1212. append_bool :: proc(buf: []byte, b: bool) -> string {
  1213. n := 0
  1214. if b {
  1215. n = copy(buf, "true")
  1216. } else {
  1217. n = copy(buf, "false")
  1218. }
  1219. return string(buf[:n])
  1220. }
  1221. /*
  1222. Appends an unsigned integer value as a string to the given buffer with the specified base
  1223. **Inputs**
  1224. - buf: The buffer to append the unsigned integer value to
  1225. - u: The unsigned integer value to be appended
  1226. - base: The base to use for converting the integer value
  1227. Example:
  1228. import "core:fmt"
  1229. import "core:strconv"
  1230. append_uint_example :: proc() {
  1231. buf: [4]byte
  1232. result := strconv.append_uint(buf[:], 42, 16)
  1233. fmt.println(result, buf)
  1234. }
  1235. Output:
  1236. 2a [50, 97, 0, 0]
  1237. **Returns**
  1238. - The resulting string after appending the unsigned integer value
  1239. */
  1240. append_uint :: proc(buf: []byte, u: u64, base: int) -> string {
  1241. return append_bits(buf, u, base, false, 8*size_of(uint), digits, nil)
  1242. }
  1243. /*
  1244. Appends a signed integer value as a string to the given buffer with the specified base
  1245. **Inputs**
  1246. - buf: The buffer to append the signed integer value to
  1247. - i: The signed integer value to be appended
  1248. - base: The base to use for converting the integer value
  1249. Example:
  1250. import "core:fmt"
  1251. import "core:strconv"
  1252. append_int_example :: proc() {
  1253. buf: [4]byte
  1254. result := strconv.append_int(buf[:], -42, 10)
  1255. fmt.println(result, buf)
  1256. }
  1257. Output:
  1258. -42 [45, 52, 50, 0]
  1259. **Returns**
  1260. - The resulting string after appending the signed integer value
  1261. */
  1262. append_int :: proc(buf: []byte, i: i64, base: int) -> string {
  1263. return append_bits(buf, u64(i), base, true, 8*size_of(int), digits, nil)
  1264. }
  1265. append_u128 :: proc(buf: []byte, u: u128, base: int) -> string {
  1266. return append_bits_128(buf, u, base, false, 8*size_of(uint), digits, nil)
  1267. }
  1268. /*
  1269. Converts an integer value to a string and stores it in the given buffer
  1270. **Inputs**
  1271. - buf: The buffer to store the resulting string
  1272. - i: The integer value to be converted
  1273. Example:
  1274. import "core:fmt"
  1275. import "core:strconv"
  1276. itoa_example :: proc() {
  1277. buf: [4]byte
  1278. result := strconv.itoa(buf[:], 42)
  1279. fmt.println(result, buf) // "42"
  1280. }
  1281. Output:
  1282. 42 [52, 50, 0, 0]
  1283. **Returns**
  1284. - The resulting string after converting the integer value
  1285. */
  1286. itoa :: proc(buf: []byte, i: int) -> string {
  1287. return append_int(buf, i64(i), 10)
  1288. }
  1289. /*
  1290. Converts a string to an integer value
  1291. **Inputs**
  1292. - s: The string to be converted
  1293. Example:
  1294. import "core:fmt"
  1295. import "core:strconv"
  1296. atoi_example :: proc() {
  1297. fmt.println(strconv.atoi("42"))
  1298. }
  1299. Output:
  1300. 42
  1301. **Returns**
  1302. - The resulting integer value
  1303. */
  1304. atoi :: proc(s: string) -> int {
  1305. v, _ := parse_int(s)
  1306. return v
  1307. }
  1308. /*
  1309. Converts a string to a float64 value
  1310. **Inputs**
  1311. - s: The string to be converted
  1312. Example:
  1313. import "core:fmt"
  1314. import "core:strconv"
  1315. atof_example :: proc() {
  1316. fmt.printfln("%.3f", strconv.atof("3.14"))
  1317. }
  1318. Output:
  1319. 3.140
  1320. **Returns**
  1321. - The resulting float64 value after converting the string
  1322. */
  1323. atof :: proc(s: string) -> f64 {
  1324. v, _ := parse_f64(s)
  1325. return v
  1326. }
  1327. // Alias to `append_float`
  1328. ftoa :: append_float
  1329. /*
  1330. Appends a float64 value as a string to the given buffer with the specified format and precision
  1331. **Inputs**
  1332. - buf: The buffer to append the float64 value to
  1333. - f: The float64 value to be appended
  1334. - fmt: The byte specifying the format to use for the conversion
  1335. - prec: The precision to use for the conversion
  1336. - bit_size: The size of the float in bits (32 or 64)
  1337. Example:
  1338. import "core:fmt"
  1339. import "core:strconv"
  1340. append_float_example :: proc() {
  1341. buf: [8]byte
  1342. result := strconv.append_float(buf[:], 3.14159, 'f', 2, 64)
  1343. fmt.println(result, buf)
  1344. }
  1345. Output:
  1346. +3.14 [43, 51, 46, 49, 52, 0, 0, 0]
  1347. **Returns**
  1348. - The resulting string after appending the float
  1349. */
  1350. append_float :: proc(buf: []byte, f: f64, fmt: byte, prec, bit_size: int) -> string {
  1351. return string(generic_ftoa(buf, f, fmt, prec, bit_size))
  1352. }
  1353. /*
  1354. Appends a quoted string representation of the input string to a given byte slice and returns the result as a string
  1355. **Inputs**
  1356. - buf: The byte slice to which the quoted string will be appended
  1357. - str: The input string to be quoted
  1358. !! ISSUE !! NOT EXPECTED -- "\"hello\"" was expected
  1359. Example:
  1360. import "core:fmt"
  1361. import "core:strconv"
  1362. quote_example :: proc() {
  1363. buf: [20]byte
  1364. result := strconv.quote(buf[:], "hello")
  1365. fmt.println(result, buf)
  1366. }
  1367. Output:
  1368. "'h''e''l''l''o'" [34, 39, 104, 39, 39, 101, 39, 39, 108, 39, 39, 108, 39, 39, 111, 39, 34, 0, 0, 0]
  1369. **Returns**
  1370. - The resulting string after appending the quoted string representation
  1371. */
  1372. quote :: proc(buf: []byte, str: string) -> string {
  1373. write_byte :: proc(buf: []byte, i: ^int, bytes: ..byte) {
  1374. if i^ >= len(buf) {
  1375. return
  1376. }
  1377. n := copy(buf[i^:], bytes[:])
  1378. i^ += n
  1379. }
  1380. if buf == nil {
  1381. return ""
  1382. }
  1383. c :: '"'
  1384. i := 0
  1385. s := str
  1386. write_byte(buf, &i, c)
  1387. for width := 0; len(s) > 0; s = s[width:] {
  1388. r := rune(s[0])
  1389. width = 1
  1390. if r >= utf8.RUNE_SELF {
  1391. r, width = utf8.decode_rune_in_string(s)
  1392. }
  1393. if width == 1 && r == utf8.RUNE_ERROR {
  1394. write_byte(buf, &i, '\\', 'x')
  1395. write_byte(buf, &i, digits[s[0]>>4])
  1396. write_byte(buf, &i, digits[s[0]&0xf])
  1397. }
  1398. if i < len(buf) {
  1399. x := quote_rune(buf[i:], r)
  1400. i += len(x)
  1401. }
  1402. }
  1403. write_byte(buf, &i, c)
  1404. return string(buf[:i])
  1405. }
  1406. /*
  1407. Appends a quoted rune representation of the input rune to a given byte slice and returns the result as a string
  1408. **Inputs**
  1409. - buf: The byte slice to which the quoted rune will be appended
  1410. - r: The input rune to be quoted
  1411. Example:
  1412. import "core:fmt"
  1413. import "core:strconv"
  1414. quote_rune_example :: proc() {
  1415. buf: [4]byte
  1416. result := strconv.quote_rune(buf[:], 'A')
  1417. fmt.println(result, buf)
  1418. }
  1419. Output:
  1420. 'A' [39, 65, 39, 0]
  1421. **Returns**
  1422. - The resulting string after appending the quoted rune representation
  1423. */
  1424. quote_rune :: proc(buf: []byte, r: rune) -> string {
  1425. write_byte :: proc(buf: []byte, i: ^int, bytes: ..byte) {
  1426. if i^ < len(buf) {
  1427. n := copy(buf[i^:], bytes[:])
  1428. i^ += n
  1429. }
  1430. }
  1431. write_string :: proc(buf: []byte, i: ^int, s: string) {
  1432. if i^ < len(buf) {
  1433. n := copy(buf[i^:], s)
  1434. i^ += n
  1435. }
  1436. }
  1437. write_rune :: proc(buf: []byte, i: ^int, r: rune) {
  1438. if i^ < len(buf) {
  1439. b, w := utf8.encode_rune(r)
  1440. n := copy(buf[i^:], b[:w])
  1441. i^ += n
  1442. }
  1443. }
  1444. if buf == nil || r < 0 {
  1445. return ""
  1446. }
  1447. i := 0
  1448. write_byte(buf, &i, '\'')
  1449. switch r {
  1450. case '\a': write_string(buf, &i, "\\a")
  1451. case '\b': write_string(buf, &i, "\\b")
  1452. case '\e': write_string(buf, &i, "\\e")
  1453. case '\f': write_string(buf, &i, "\\f")
  1454. case '\n': write_string(buf, &i, "\\n")
  1455. case '\r': write_string(buf, &i, "\\r")
  1456. case '\t': write_string(buf, &i, "\\t")
  1457. case '\v': write_string(buf, &i, "\\v")
  1458. case:
  1459. if r < 32 {
  1460. write_string(buf, &i, "\\x")
  1461. b: [2]byte
  1462. s := append_bits(b[:], u64(r), 16, true, 64, digits, nil)
  1463. switch len(s) {
  1464. case 0: write_string(buf, &i, "00")
  1465. case 1: write_rune(buf, &i, '0')
  1466. case 2: write_string(buf, &i, s)
  1467. }
  1468. } else {
  1469. write_rune(buf, &i, r)
  1470. }
  1471. }
  1472. write_byte(buf, &i, '\'')
  1473. return string(buf[:i])
  1474. }
  1475. /*
  1476. Unquotes a single character from the input string, considering the given quote character
  1477. **Inputs**
  1478. - str: The input string containing the character to unquote
  1479. - quote: The quote character to consider (e.g., '"')
  1480. Example:
  1481. import "core:fmt"
  1482. import "core:strconv"
  1483. unquote_char_example :: proc() {
  1484. src:="\'The\' raven"
  1485. r, multiple_bytes, tail_string, success := strconv.unquote_char(src,'\'')
  1486. fmt.println("Source:", src)
  1487. fmt.printf("r: <%v>, multiple_bytes:%v, tail_string:<%s>, success:%v\n",r, multiple_bytes, tail_string, success)
  1488. }
  1489. Output:
  1490. Source: 'The' raven
  1491. r: <'>, multiple_bytes:false, tail_string:<The' raven>, success:true
  1492. **Returns**
  1493. - r: The unquoted rune
  1494. - multiple_bytes: A boolean indicating if the rune has multiple bytes
  1495. - tail_string: The remaining portion of the input string after unquoting the character
  1496. - success: A boolean indicating whether the unquoting was successful
  1497. */
  1498. unquote_char :: proc(str: string, quote: byte) -> (r: rune, multiple_bytes: bool, tail_string: string, success: bool) {
  1499. hex_to_int :: proc(c: byte) -> int {
  1500. switch c {
  1501. case '0'..='9': return int(c-'0')
  1502. case 'a'..='f': return int(c-'a')+10
  1503. case 'A'..='F': return int(c-'A')+10
  1504. }
  1505. return -1
  1506. }
  1507. w: int
  1508. if str[0] == quote && quote == '"' {
  1509. return
  1510. } else if str[0] >= 0x80 {
  1511. r, w = utf8.decode_rune_in_string(str)
  1512. return r, true, str[w:], true
  1513. } else if str[0] != '\\' {
  1514. return rune(str[0]), false, str[1:], true
  1515. }
  1516. if len(str) <= 1 {
  1517. return
  1518. }
  1519. s := str
  1520. c := s[1]
  1521. s = s[2:]
  1522. switch c {
  1523. case:
  1524. return
  1525. case 'a': r = '\a'
  1526. case 'b': r = '\b'
  1527. case 'f': r = '\f'
  1528. case 'n': r = '\n'
  1529. case 'r': r = '\r'
  1530. case 't': r = '\t'
  1531. case 'v': r = '\v'
  1532. case '\\': r = '\\'
  1533. case '"': r = '"'
  1534. case '\'': r = '\''
  1535. case '0'..='7':
  1536. v := int(c-'0')
  1537. if len(s) < 2 {
  1538. return
  1539. }
  1540. for i in 0..<len(s) {
  1541. d := int(s[i]-'0')
  1542. if d < 0 || d > 7 {
  1543. return
  1544. }
  1545. v = (v<<3) | d
  1546. }
  1547. s = s[2:]
  1548. if v > 0xff {
  1549. return
  1550. }
  1551. r = rune(v)
  1552. case 'x', 'u', 'U':
  1553. count: int
  1554. switch c {
  1555. case 'x': count = 2
  1556. case 'u': count = 4
  1557. case 'U': count = 8
  1558. }
  1559. if len(s) < count {
  1560. return
  1561. }
  1562. for i in 0..<count {
  1563. d := hex_to_int(s[i])
  1564. if d < 0 {
  1565. return
  1566. }
  1567. r = (r<<4) | rune(d)
  1568. }
  1569. s = s[count:]
  1570. if c == 'x' {
  1571. break
  1572. }
  1573. if r > utf8.MAX_RUNE {
  1574. return
  1575. }
  1576. multiple_bytes = true
  1577. }
  1578. success = true
  1579. tail_string = s
  1580. return
  1581. }
  1582. /*
  1583. Unquotes the input string considering any type of quote character and returns the unquoted string
  1584. **Inputs**
  1585. - lit: The input string to unquote
  1586. - allocator: (default: context.allocator)
  1587. WARNING: This procedure gives unexpected results if the quotes are not the first and last characters.
  1588. Example:
  1589. import "core:fmt"
  1590. import "core:strconv"
  1591. unquote_string_example :: proc() {
  1592. src:="\"The raven Huginn is black.\""
  1593. s, allocated, ok := strconv.unquote_string(src)
  1594. fmt.println(src)
  1595. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n\n", s, allocated, ok)
  1596. src="\'The raven Huginn\' is black."
  1597. s, allocated, ok = strconv.unquote_string(src)
  1598. fmt.println(src)
  1599. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n\n", s, allocated, ok)
  1600. src="The raven \'Huginn\' is black."
  1601. s, allocated, ok = strconv.unquote_string(src) // Will produce undesireable results
  1602. fmt.println(src)
  1603. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n", s, allocated, ok)
  1604. }
  1605. Output:
  1606. "The raven Huginn is black."
  1607. Unquoted: <The raven Huginn is black.>, alloc:false, ok:true
  1608. 'The raven Huginn' is black.
  1609. Unquoted: <The raven Huginn' is black>, alloc:false, ok:true
  1610. The raven 'Huginn' is black.
  1611. Unquoted: <he raven 'Huginn' is black>, alloc:false, ok:true
  1612. **Returns**
  1613. - res: The resulting unquoted string
  1614. - allocated: A boolean indicating if the resulting string was allocated using the provided allocator
  1615. - success: A boolean indicating whether the unquoting was successful
  1616. NOTE: If unquoting is unsuccessful, the allocated memory for the result will be freed.
  1617. */
  1618. unquote_string :: proc(lit: string, allocator := context.allocator) -> (res: string, allocated, success: bool) {
  1619. contains_rune :: proc(s: string, r: rune) -> int {
  1620. for c, offset in s {
  1621. if c == r {
  1622. return offset
  1623. }
  1624. }
  1625. return -1
  1626. }
  1627. if len(lit) < 2 {
  1628. return
  1629. }
  1630. if lit[0] == '`' {
  1631. return lit[1:len(lit)-1], false, true
  1632. }
  1633. s := lit
  1634. quote := '"'
  1635. if s == `""` {
  1636. return "", false, true
  1637. }
  1638. s = s[1:len(s)-1]
  1639. if contains_rune(s, '\n') >= 0 {
  1640. return s, false, false
  1641. }
  1642. if contains_rune(s, '\\') < 0 && contains_rune(s, quote) < 0 {
  1643. if quote == '"' {
  1644. return s, false, true
  1645. }
  1646. }
  1647. context.allocator = allocator
  1648. buf_len := 3*len(s) / 2
  1649. buf := make([]byte, buf_len)
  1650. offset := 0
  1651. for len(s) > 0 {
  1652. r, multiple_bytes, tail_string, ok := unquote_char(s, byte(quote))
  1653. if !ok {
  1654. delete(buf)
  1655. return s, false, false
  1656. }
  1657. s = tail_string
  1658. if r < 0x80 || !multiple_bytes {
  1659. buf[offset] = byte(r)
  1660. offset += 1
  1661. } else {
  1662. b, w := utf8.encode_rune(r)
  1663. copy(buf[offset:], b[:w])
  1664. offset += w
  1665. }
  1666. }
  1667. new_string := string(buf[:offset])
  1668. return new_string, true, true
  1669. }