strconv.odin 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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. if neg {
  956. f = -f
  957. }
  958. switch {
  959. case exp == 0:
  960. return f, nr, true
  961. case exp > 0 && exp <= 15+22:
  962. if exp > 22 {
  963. f *= pow10[exp-22]
  964. exp = 22
  965. }
  966. if f > 1e15 || f < 1e-15 {
  967. break trunc_block
  968. }
  969. return f * pow10[exp], nr, true
  970. case -22 <= exp && exp < 0:
  971. return f / pow10[-exp], nr, true
  972. }
  973. }
  974. d: decimal.Decimal
  975. decimal.set(&d, str[:nr])
  976. b, overflow := decimal_to_float_bits(&d, &_f64_info)
  977. value = transmute(f64)b
  978. ok = !overflow
  979. return
  980. }
  981. /*
  982. Parses a 128-bit complex number from a string
  983. **Inputs**
  984. - str: The input string containing a 128-bit complex number.
  985. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  986. Example:
  987. import "core:fmt"
  988. import "core:strconv"
  989. parse_complex128_example :: proc() {
  990. n: int
  991. c, ok := strconv.parse_complex128("3+1i", &n)
  992. fmt.printfln("%v %i %t", c, n, ok)
  993. c, ok = strconv.parse_complex128("5+7i hellope", &n)
  994. fmt.printfln("%v %i %t", c, n, ok)
  995. }
  996. Output:
  997. 3+1i 4 true
  998. 5+7i 4 false
  999. **Returns**
  1000. - value: The parsed 128-bit complex number.
  1001. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1002. */
  1003. parse_complex128 :: proc(str: string, n: ^int = nil) -> (value: complex128, ok: bool) {
  1004. real_value, imag_value: f64
  1005. nr_r, nr_i: int
  1006. real_value, nr_r, _ = parse_f64_prefix(str)
  1007. imag_value, nr_i, _ = parse_f64_prefix(str[nr_r:])
  1008. i_parsed := len(str) >= nr_r + nr_i + 1 && str[nr_r + nr_i] == 'i'
  1009. if !i_parsed {
  1010. // No `i` means we refuse to treat the second float we parsed as an
  1011. // imaginary value.
  1012. imag_value = 0
  1013. nr_i = 0
  1014. }
  1015. ok = i_parsed && len(str) == nr_r + nr_i + 1
  1016. if n != nil {
  1017. n^ = nr_r + nr_i + (1 if i_parsed else 0)
  1018. }
  1019. value = complex(real_value, imag_value)
  1020. return
  1021. }
  1022. /*
  1023. Parses a 64-bit complex number from a string
  1024. **Inputs**
  1025. - str: The input string containing a 64-bit complex number.
  1026. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1027. Example:
  1028. import "core:fmt"
  1029. import "core:strconv"
  1030. parse_complex64_example :: proc() {
  1031. n: int
  1032. c, ok := strconv.parse_complex64("3+1i", &n)
  1033. fmt.printfln("%v %i %t", c, n, ok)
  1034. c, ok = strconv.parse_complex64("5+7i hellope", &n)
  1035. fmt.printfln("%v %i %t", c, n, ok)
  1036. }
  1037. Output:
  1038. 3+1i 4 true
  1039. 5+7i 4 false
  1040. **Returns**
  1041. - value: The parsed 64-bit complex number.
  1042. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1043. */
  1044. parse_complex64 :: proc(str: string, n: ^int = nil) -> (value: complex64, ok: bool) {
  1045. v: complex128 = ---
  1046. v, ok = parse_complex128(str, n)
  1047. return cast(complex64)v, ok
  1048. }
  1049. /*
  1050. Parses a 32-bit complex number from a string
  1051. **Inputs**
  1052. - str: The input string containing a 32-bit complex number.
  1053. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1054. Example:
  1055. import "core:fmt"
  1056. import "core:strconv"
  1057. parse_complex32_example :: proc() {
  1058. n: int
  1059. c, ok := strconv.parse_complex32("3+1i", &n)
  1060. fmt.printfln("%v %i %t", c, n, ok)
  1061. c, ok = strconv.parse_complex32("5+7i hellope", &n)
  1062. fmt.printfln("%v %i %t", c, n, ok)
  1063. }
  1064. Output:
  1065. 3+1i 4 true
  1066. 5+7i 4 false
  1067. **Returns**
  1068. - value: The parsed 32-bit complex number.
  1069. - ok: `false` if a complex number could not be found, or if the input string contained more than just the number.
  1070. */
  1071. parse_complex32 :: proc(str: string, n: ^int = nil) -> (value: complex32, ok: bool) {
  1072. v: complex128 = ---
  1073. v, ok = parse_complex128(str, n)
  1074. return cast(complex32)v, ok
  1075. }
  1076. /*
  1077. Parses a 256-bit quaternion from a string
  1078. **Inputs**
  1079. - str: The input string containing a 256-bit quaternion.
  1080. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1081. Example:
  1082. import "core:fmt"
  1083. import "core:strconv"
  1084. parse_quaternion256_example :: proc() {
  1085. n: int
  1086. q, ok := strconv.parse_quaternion256("1+2i+3j+4k", &n)
  1087. fmt.printfln("%v %i %t", q, n, ok)
  1088. q, ok = strconv.parse_quaternion256("1+2i+3j+4k hellope", &n)
  1089. fmt.printfln("%v %i %t", q, n, ok)
  1090. }
  1091. Output:
  1092. 1+2i+3j+4k 10 true
  1093. 1+2i+3j+4k 10 false
  1094. **Returns**
  1095. - value: The parsed 256-bit quaternion.
  1096. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1097. */
  1098. parse_quaternion256 :: proc(str: string, n: ^int = nil) -> (value: quaternion256, ok: bool) {
  1099. iterate_and_assign :: proc (iter: ^string, terminator: byte, nr_total: ^int, state: bool) -> (value: f64, ok: bool) {
  1100. if !state {
  1101. return
  1102. }
  1103. nr: int
  1104. value, nr, _ = parse_f64_prefix(iter^)
  1105. iter^ = iter[nr:]
  1106. if len(iter) > 0 && iter[0] == terminator {
  1107. iter^ = iter[1:]
  1108. nr_total^ += nr + 1
  1109. ok = true
  1110. } else {
  1111. value = 0
  1112. }
  1113. return
  1114. }
  1115. real_value, imag_value, jmag_value, kmag_value: f64
  1116. nr: int
  1117. real_value, nr, _ = parse_f64_prefix(str)
  1118. iter := str[nr:]
  1119. // Need to have parsed at least something in order to get started.
  1120. ok = nr > 0
  1121. // Quaternion parsing is done this way to honour the rest of the API with
  1122. // regards to partial parsing. Otherwise, we could error out early.
  1123. imag_value, ok = iterate_and_assign(&iter, 'i', &nr, ok)
  1124. jmag_value, ok = iterate_and_assign(&iter, 'j', &nr, ok)
  1125. kmag_value, ok = iterate_and_assign(&iter, 'k', &nr, ok)
  1126. if len(iter) != 0 {
  1127. ok = false
  1128. }
  1129. if n != nil {
  1130. n^ = nr
  1131. }
  1132. value = quaternion(
  1133. real = real_value,
  1134. imag = imag_value,
  1135. jmag = jmag_value,
  1136. kmag = kmag_value)
  1137. return
  1138. }
  1139. /*
  1140. Parses a 128-bit quaternion from a string
  1141. **Inputs**
  1142. - str: The input string containing a 128-bit quaternion.
  1143. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1144. Example:
  1145. import "core:fmt"
  1146. import "core:strconv"
  1147. parse_quaternion128_example :: proc() {
  1148. n: int
  1149. q, ok := strconv.parse_quaternion128("1+2i+3j+4k", &n)
  1150. fmt.printfln("%v %i %t", q, n, ok)
  1151. q, ok = strconv.parse_quaternion128("1+2i+3j+4k hellope", &n)
  1152. fmt.printfln("%v %i %t", q, n, ok)
  1153. }
  1154. Output:
  1155. 1+2i+3j+4k 10 true
  1156. 1+2i+3j+4k 10 false
  1157. **Returns**
  1158. - value: The parsed 128-bit quaternion.
  1159. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1160. */
  1161. parse_quaternion128 :: proc(str: string, n: ^int = nil) -> (value: quaternion128, ok: bool) {
  1162. v: quaternion256 = ---
  1163. v, ok = parse_quaternion256(str, n)
  1164. return cast(quaternion128)v, ok
  1165. }
  1166. /*
  1167. Parses a 64-bit quaternion from a string
  1168. **Inputs**
  1169. - str: The input string containing a 64-bit quaternion.
  1170. - n: An optional pointer to an int to store the length of the parsed substring (default: nil).
  1171. Example:
  1172. import "core:fmt"
  1173. import "core:strconv"
  1174. parse_quaternion64_example :: proc() {
  1175. n: int
  1176. q, ok := strconv.parse_quaternion64("1+2i+3j+4k", &n)
  1177. fmt.printfln("%v %i %t", q, n, ok)
  1178. q, ok = strconv.parse_quaternion64("1+2i+3j+4k hellope", &n)
  1179. fmt.printfln("%v %i %t", q, n, ok)
  1180. }
  1181. Output:
  1182. 1+2i+3j+4k 10 true
  1183. 1+2i+3j+4k 10 false
  1184. **Returns**
  1185. - value: The parsed 64-bit quaternion.
  1186. - ok: `false` if a quaternion could not be found, or if the input string contained more than just the quaternion.
  1187. */
  1188. parse_quaternion64 :: proc(str: string, n: ^int = nil) -> (value: quaternion64, ok: bool) {
  1189. v: quaternion256 = ---
  1190. v, ok = parse_quaternion256(str, n)
  1191. return cast(quaternion64)v, ok
  1192. }
  1193. /*
  1194. Appends a boolean value as a string to the given buffer
  1195. **Inputs**
  1196. - buf: The buffer to append the boolean value to
  1197. - b: The boolean value to be appended
  1198. Example:
  1199. import "core:fmt"
  1200. import "core:strconv"
  1201. append_bool_example :: proc() {
  1202. buf: [6]byte
  1203. result := strconv.append_bool(buf[:], true)
  1204. fmt.println(result, buf)
  1205. }
  1206. Output:
  1207. true [116, 114, 117, 101, 0, 0]
  1208. **Returns**
  1209. - The resulting string after appending the boolean value
  1210. */
  1211. append_bool :: proc(buf: []byte, b: bool) -> string {
  1212. n := 0
  1213. if b {
  1214. n = copy(buf, "true")
  1215. } else {
  1216. n = copy(buf, "false")
  1217. }
  1218. return string(buf[:n])
  1219. }
  1220. /*
  1221. Appends an unsigned integer value as a string to the given buffer with the specified base
  1222. **Inputs**
  1223. - buf: The buffer to append the unsigned integer value to
  1224. - u: The unsigned integer value to be appended
  1225. - base: The base to use for converting the integer value
  1226. Example:
  1227. import "core:fmt"
  1228. import "core:strconv"
  1229. append_uint_example :: proc() {
  1230. buf: [4]byte
  1231. result := strconv.append_uint(buf[:], 42, 16)
  1232. fmt.println(result, buf)
  1233. }
  1234. Output:
  1235. 2a [50, 97, 0, 0]
  1236. **Returns**
  1237. - The resulting string after appending the unsigned integer value
  1238. */
  1239. append_uint :: proc(buf: []byte, u: u64, base: int) -> string {
  1240. return append_bits(buf, u, base, false, 8*size_of(uint), digits, nil)
  1241. }
  1242. /*
  1243. Appends a signed integer value as a string to the given buffer with the specified base
  1244. **Inputs**
  1245. - buf: The buffer to append the signed integer value to
  1246. - i: The signed integer value to be appended
  1247. - base: The base to use for converting the integer value
  1248. Example:
  1249. import "core:fmt"
  1250. import "core:strconv"
  1251. append_int_example :: proc() {
  1252. buf: [4]byte
  1253. result := strconv.append_int(buf[:], -42, 10)
  1254. fmt.println(result, buf)
  1255. }
  1256. Output:
  1257. -42 [45, 52, 50, 0]
  1258. **Returns**
  1259. - The resulting string after appending the signed integer value
  1260. */
  1261. append_int :: proc(buf: []byte, i: i64, base: int) -> string {
  1262. return append_bits(buf, u64(i), base, true, 8*size_of(int), digits, nil)
  1263. }
  1264. append_u128 :: proc(buf: []byte, u: u128, base: int) -> string {
  1265. return append_bits_128(buf, u, base, false, 8*size_of(uint), digits, nil)
  1266. }
  1267. /*
  1268. Converts an integer value to a string and stores it in the given buffer
  1269. **Inputs**
  1270. - buf: The buffer to store the resulting string
  1271. - i: The integer value to be converted
  1272. Example:
  1273. import "core:fmt"
  1274. import "core:strconv"
  1275. itoa_example :: proc() {
  1276. buf: [4]byte
  1277. result := strconv.itoa(buf[:], 42)
  1278. fmt.println(result, buf) // "42"
  1279. }
  1280. Output:
  1281. 42 [52, 50, 0, 0]
  1282. **Returns**
  1283. - The resulting string after converting the integer value
  1284. */
  1285. itoa :: proc(buf: []byte, i: int) -> string {
  1286. return append_int(buf, i64(i), 10)
  1287. }
  1288. /*
  1289. Converts a string to an integer value
  1290. **Inputs**
  1291. - s: The string to be converted
  1292. Example:
  1293. import "core:fmt"
  1294. import "core:strconv"
  1295. atoi_example :: proc() {
  1296. fmt.println(strconv.atoi("42"))
  1297. }
  1298. Output:
  1299. 42
  1300. **Returns**
  1301. - The resulting integer value
  1302. */
  1303. atoi :: proc(s: string) -> int {
  1304. v, _ := parse_int(s)
  1305. return v
  1306. }
  1307. /*
  1308. Converts a string to a float64 value
  1309. **Inputs**
  1310. - s: The string to be converted
  1311. Example:
  1312. import "core:fmt"
  1313. import "core:strconv"
  1314. atof_example :: proc() {
  1315. fmt.printfln("%.3f", strconv.atof("3.14"))
  1316. }
  1317. Output:
  1318. 3.140
  1319. **Returns**
  1320. - The resulting float64 value after converting the string
  1321. */
  1322. atof :: proc(s: string) -> f64 {
  1323. v, _ := parse_f64(s)
  1324. return v
  1325. }
  1326. // Alias to `append_float`
  1327. ftoa :: append_float
  1328. /*
  1329. Appends a float64 value as a string to the given buffer with the specified format and precision
  1330. **Inputs**
  1331. - buf: The buffer to append the float64 value to
  1332. - f: The float64 value to be appended
  1333. - fmt: The byte specifying the format to use for the conversion
  1334. - prec: The precision to use for the conversion
  1335. - bit_size: The size of the float in bits (32 or 64)
  1336. Example:
  1337. import "core:fmt"
  1338. import "core:strconv"
  1339. append_float_example :: proc() {
  1340. buf: [8]byte
  1341. result := strconv.append_float(buf[:], 3.14159, 'f', 2, 64)
  1342. fmt.println(result, buf)
  1343. }
  1344. Output:
  1345. +3.14 [43, 51, 46, 49, 52, 0, 0, 0]
  1346. **Returns**
  1347. - The resulting string after appending the float
  1348. */
  1349. append_float :: proc(buf: []byte, f: f64, fmt: byte, prec, bit_size: int) -> string {
  1350. return string(generic_ftoa(buf, f, fmt, prec, bit_size))
  1351. }
  1352. /*
  1353. Appends a quoted string representation of the input string to a given byte slice and returns the result as a string
  1354. **Inputs**
  1355. - buf: The byte slice to which the quoted string will be appended
  1356. - str: The input string to be quoted
  1357. !! ISSUE !! NOT EXPECTED -- "\"hello\"" was expected
  1358. Example:
  1359. import "core:fmt"
  1360. import "core:strconv"
  1361. quote_example :: proc() {
  1362. buf: [20]byte
  1363. result := strconv.quote(buf[:], "hello")
  1364. fmt.println(result, buf)
  1365. }
  1366. Output:
  1367. "'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]
  1368. **Returns**
  1369. - The resulting string after appending the quoted string representation
  1370. */
  1371. quote :: proc(buf: []byte, str: string) -> string {
  1372. write_byte :: proc(buf: []byte, i: ^int, bytes: ..byte) {
  1373. if i^ >= len(buf) {
  1374. return
  1375. }
  1376. n := copy(buf[i^:], bytes[:])
  1377. i^ += n
  1378. }
  1379. if buf == nil {
  1380. return ""
  1381. }
  1382. c :: '"'
  1383. i := 0
  1384. s := str
  1385. write_byte(buf, &i, c)
  1386. for width := 0; len(s) > 0; s = s[width:] {
  1387. r := rune(s[0])
  1388. width = 1
  1389. if r >= utf8.RUNE_SELF {
  1390. r, width = utf8.decode_rune_in_string(s)
  1391. }
  1392. if width == 1 && r == utf8.RUNE_ERROR {
  1393. write_byte(buf, &i, '\\', 'x')
  1394. write_byte(buf, &i, digits[s[0]>>4])
  1395. write_byte(buf, &i, digits[s[0]&0xf])
  1396. }
  1397. if i < len(buf) {
  1398. x := quote_rune(buf[i:], r)
  1399. i += len(x)
  1400. }
  1401. }
  1402. write_byte(buf, &i, c)
  1403. return string(buf[:i])
  1404. }
  1405. /*
  1406. Appends a quoted rune representation of the input rune to a given byte slice and returns the result as a string
  1407. **Inputs**
  1408. - buf: The byte slice to which the quoted rune will be appended
  1409. - r: The input rune to be quoted
  1410. Example:
  1411. import "core:fmt"
  1412. import "core:strconv"
  1413. quote_rune_example :: proc() {
  1414. buf: [4]byte
  1415. result := strconv.quote_rune(buf[:], 'A')
  1416. fmt.println(result, buf)
  1417. }
  1418. Output:
  1419. 'A' [39, 65, 39, 0]
  1420. **Returns**
  1421. - The resulting string after appending the quoted rune representation
  1422. */
  1423. quote_rune :: proc(buf: []byte, r: rune) -> string {
  1424. write_byte :: proc(buf: []byte, i: ^int, bytes: ..byte) {
  1425. if i^ < len(buf) {
  1426. n := copy(buf[i^:], bytes[:])
  1427. i^ += n
  1428. }
  1429. }
  1430. write_string :: proc(buf: []byte, i: ^int, s: string) {
  1431. if i^ < len(buf) {
  1432. n := copy(buf[i^:], s)
  1433. i^ += n
  1434. }
  1435. }
  1436. write_rune :: proc(buf: []byte, i: ^int, r: rune) {
  1437. if i^ < len(buf) {
  1438. b, w := utf8.encode_rune(r)
  1439. n := copy(buf[i^:], b[:w])
  1440. i^ += n
  1441. }
  1442. }
  1443. if buf == nil {
  1444. return ""
  1445. }
  1446. i := 0
  1447. write_byte(buf, &i, '\'')
  1448. switch r {
  1449. case '\a': write_string(buf, &i, "\\a")
  1450. case '\b': write_string(buf, &i, "\\b")
  1451. case '\e': write_string(buf, &i, "\\e")
  1452. case '\f': write_string(buf, &i, "\\f")
  1453. case '\n': write_string(buf, &i, "\\n")
  1454. case '\r': write_string(buf, &i, "\\r")
  1455. case '\t': write_string(buf, &i, "\\t")
  1456. case '\v': write_string(buf, &i, "\\v")
  1457. case:
  1458. if r < 32 {
  1459. write_string(buf, &i, "\\x")
  1460. b: [2]byte
  1461. s := append_bits(b[:], u64(r), 16, true, 64, digits, nil)
  1462. switch len(s) {
  1463. case 0: write_string(buf, &i, "00")
  1464. case 1: write_rune(buf, &i, '0')
  1465. case 2: write_string(buf, &i, s)
  1466. }
  1467. } else {
  1468. write_rune(buf, &i, r)
  1469. }
  1470. }
  1471. write_byte(buf, &i, '\'')
  1472. return string(buf[:i])
  1473. }
  1474. /*
  1475. Unquotes a single character from the input string, considering the given quote character
  1476. **Inputs**
  1477. - str: The input string containing the character to unquote
  1478. - quote: The quote character to consider (e.g., '"')
  1479. Example:
  1480. import "core:fmt"
  1481. import "core:strconv"
  1482. unquote_char_example :: proc() {
  1483. src:="\'The\' raven"
  1484. r, multiple_bytes, tail_string, success := strconv.unquote_char(src,'\'')
  1485. fmt.println("Source:", src)
  1486. fmt.printf("r: <%v>, multiple_bytes:%v, tail_string:<%s>, success:%v\n",r, multiple_bytes, tail_string, success)
  1487. }
  1488. Output:
  1489. Source: 'The' raven
  1490. r: <'>, multiple_bytes:false, tail_string:<The' raven>, success:true
  1491. **Returns**
  1492. - r: The unquoted rune
  1493. - multiple_bytes: A boolean indicating if the rune has multiple bytes
  1494. - tail_string: The remaining portion of the input string after unquoting the character
  1495. - success: A boolean indicating whether the unquoting was successful
  1496. */
  1497. unquote_char :: proc(str: string, quote: byte) -> (r: rune, multiple_bytes: bool, tail_string: string, success: bool) {
  1498. hex_to_int :: proc(c: byte) -> int {
  1499. switch c {
  1500. case '0'..='9': return int(c-'0')
  1501. case 'a'..='f': return int(c-'a')+10
  1502. case 'A'..='F': return int(c-'A')+10
  1503. }
  1504. return -1
  1505. }
  1506. w: int
  1507. if str[0] == quote && quote == '"' {
  1508. return
  1509. } else if str[0] >= 0x80 {
  1510. r, w = utf8.decode_rune_in_string(str)
  1511. return r, true, str[w:], true
  1512. } else if str[0] != '\\' {
  1513. return rune(str[0]), false, str[1:], true
  1514. }
  1515. if len(str) <= 1 {
  1516. return
  1517. }
  1518. s := str
  1519. c := s[1]
  1520. s = s[2:]
  1521. switch c {
  1522. case:
  1523. return
  1524. case 'a': r = '\a'
  1525. case 'b': r = '\b'
  1526. case 'f': r = '\f'
  1527. case 'n': r = '\n'
  1528. case 'r': r = '\r'
  1529. case 't': r = '\t'
  1530. case 'v': r = '\v'
  1531. case '\\': r = '\\'
  1532. case '"': r = '"'
  1533. case '\'': r = '\''
  1534. case '0'..='7':
  1535. v := int(c-'0')
  1536. if len(s) < 2 {
  1537. return
  1538. }
  1539. for i in 0..<len(s) {
  1540. d := int(s[i]-'0')
  1541. if d < 0 || d > 7 {
  1542. return
  1543. }
  1544. v = (v<<3) | d
  1545. }
  1546. s = s[2:]
  1547. if v > 0xff {
  1548. return
  1549. }
  1550. r = rune(v)
  1551. case 'x', 'u', 'U':
  1552. count: int
  1553. switch c {
  1554. case 'x': count = 2
  1555. case 'u': count = 4
  1556. case 'U': count = 8
  1557. }
  1558. if len(s) < count {
  1559. return
  1560. }
  1561. for i in 0..<count {
  1562. d := hex_to_int(s[i])
  1563. if d < 0 {
  1564. return
  1565. }
  1566. r = (r<<4) | rune(d)
  1567. }
  1568. s = s[count:]
  1569. if c == 'x' {
  1570. break
  1571. }
  1572. if r > utf8.MAX_RUNE {
  1573. return
  1574. }
  1575. multiple_bytes = true
  1576. }
  1577. success = true
  1578. tail_string = s
  1579. return
  1580. }
  1581. /*
  1582. Unquotes the input string considering any type of quote character and returns the unquoted string
  1583. **Inputs**
  1584. - lit: The input string to unquote
  1585. - allocator: (default: context.allocator)
  1586. WARNING: This procedure gives unexpected results if the quotes are not the first and last characters.
  1587. Example:
  1588. import "core:fmt"
  1589. import "core:strconv"
  1590. unquote_string_example :: proc() {
  1591. src:="\"The raven Huginn is black.\""
  1592. s, allocated, ok := strconv.unquote_string(src)
  1593. fmt.println(src)
  1594. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n\n", s, allocated, ok)
  1595. src="\'The raven Huginn\' is black."
  1596. s, allocated, ok = strconv.unquote_string(src)
  1597. fmt.println(src)
  1598. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n\n", s, allocated, ok)
  1599. src="The raven \'Huginn\' is black."
  1600. s, allocated, ok = strconv.unquote_string(src) // Will produce undesireable results
  1601. fmt.println(src)
  1602. fmt.printf("Unquoted: <%s>, alloc:%v, ok:%v\n", s, allocated, ok)
  1603. }
  1604. Output:
  1605. "The raven Huginn is black."
  1606. Unquoted: <The raven Huginn is black.>, alloc:false, ok:true
  1607. 'The raven Huginn' is black.
  1608. Unquoted: <The raven Huginn' is black>, alloc:false, ok:true
  1609. The raven 'Huginn' is black.
  1610. Unquoted: <he raven 'Huginn' is black>, alloc:false, ok:true
  1611. **Returns**
  1612. - res: The resulting unquoted string
  1613. - allocated: A boolean indicating if the resulting string was allocated using the provided allocator
  1614. - success: A boolean indicating whether the unquoting was successful
  1615. NOTE: If unquoting is unsuccessful, the allocated memory for the result will be freed.
  1616. */
  1617. unquote_string :: proc(lit: string, allocator := context.allocator) -> (res: string, allocated, success: bool) {
  1618. contains_rune :: proc(s: string, r: rune) -> int {
  1619. for c, offset in s {
  1620. if c == r {
  1621. return offset
  1622. }
  1623. }
  1624. return -1
  1625. }
  1626. if len(lit) < 2 {
  1627. return
  1628. }
  1629. if lit[0] == '`' {
  1630. return lit[1:len(lit)-1], false, true
  1631. }
  1632. s := lit
  1633. quote := '"'
  1634. if s == `""` {
  1635. return "", false, true
  1636. }
  1637. s = s[1:len(s)-1]
  1638. if contains_rune(s, '\n') >= 0 {
  1639. return s, false, false
  1640. }
  1641. if contains_rune(s, '\\') < 0 && contains_rune(s, quote) < 0 {
  1642. if quote == '"' {
  1643. return s, false, true
  1644. }
  1645. }
  1646. context.allocator = allocator
  1647. buf_len := 3*len(s) / 2
  1648. buf := make([]byte, buf_len)
  1649. offset := 0
  1650. for len(s) > 0 {
  1651. r, multiple_bytes, tail_string, ok := unquote_char(s, byte(quote))
  1652. if !ok {
  1653. delete(buf)
  1654. return s, false, false
  1655. }
  1656. s = tail_string
  1657. if r < 0x80 || !multiple_bytes {
  1658. buf[offset] = byte(r)
  1659. offset += 1
  1660. } else {
  1661. b, w := utf8.encode_rune(r)
  1662. copy(buf[offset:], b[:w])
  1663. offset += w
  1664. }
  1665. }
  1666. new_string := string(buf[:offset])
  1667. return new_string, true, true
  1668. }