xprintf.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. /*------------------------------------------------------------------------/
  2. / Universal String Handler for Console Input and Output
  3. /-------------------------------------------------------------------------/
  4. /
  5. / Copyright (C) 2021, ChaN, all right reserved.
  6. /
  7. / xprintf module is an open source software. Redistribution and use of
  8. / xprintf module in source and binary forms, with or without modification,
  9. / are permitted provided that the following condition is met:
  10. /
  11. / 1. Redistributions of source code must retain the above copyright notice,
  12. / this condition and the following disclaimer.
  13. /
  14. / This software is provided by the copyright holder and contributors "AS IS"
  15. / and any warranties related to this software are DISCLAIMED.
  16. / The copyright owner or contributors be NOT LIABLE for any damages caused
  17. / by use of this software.
  18. /
  19. /-------------------------------------------------------------------------*/
  20. #include "xprintf.h"
  21. #include <avr/pgmspace.h>
  22. #define SZB_OUTPUT 32
  23. #if XF_USE_OUTPUT
  24. #include <stdarg.h>
  25. void (*xfunc_output)(int); /* Pointer to the default output device */
  26. static char *strptr; /* Pointer to the output memory (used by xsprintf) */
  27. #if XF_USE_FP
  28. /*----------------------------------------------*/
  29. /* Floating point output */
  30. /*----------------------------------------------*/
  31. #include <math.h>
  32. static int ilog10 (double n) /* Calculate log10(n) in integer output */
  33. {
  34. int rv = 0;
  35. while (n >= 10) { /* Decimate digit in right shift */
  36. if (n >= 100000) {
  37. n /= 100000; rv += 5;
  38. } else {
  39. n /= 10; rv++;
  40. }
  41. }
  42. while (n < 1) { /* Decimate digit in left shift */
  43. if (n < 0.00001) {
  44. n *= 100000; rv -= 5;
  45. } else {
  46. n *= 10; rv--;
  47. }
  48. }
  49. return rv;
  50. }
  51. static double i10x (int n) /* Calculate 10^n */
  52. {
  53. double rv = 1;
  54. while (n > 0) { /* Left shift */
  55. if (n >= 5) {
  56. rv *= 100000; n -= 5;
  57. } else {
  58. rv *= 10; n--;
  59. }
  60. }
  61. while (n < 0) { /* Right shift */
  62. if (n <= -5) {
  63. rv /= 100000; n += 5;
  64. } else {
  65. rv /= 10; n++;
  66. }
  67. }
  68. return rv;
  69. }
  70. static void ftoa (
  71. char* buf, /* Buffer to output the generated string */
  72. double val, /* Real number to output */
  73. int prec, /* Number of fractinal digits */
  74. char fmt /* Notation */
  75. )
  76. {
  77. int d;
  78. int e = 0, m = 0;
  79. char sign = 0;
  80. double w;
  81. const char *er = 0;
  82. if (isnan(val)) { /* Not a number? */
  83. er = "NaN";
  84. } else {
  85. if (prec < 0) prec = 6; /* Default precision (6 fractional digits) */
  86. if (val < 0) { /* Nagative value? */
  87. val = -val; sign = '-';
  88. } else {
  89. sign = '+';
  90. }
  91. if (isinf(val)) { /* Infinite? */
  92. er = "INF";
  93. } else {
  94. if (fmt == 'f') { /* Decimal notation? */
  95. val += i10x(-prec) / 2; /* Round (nearest) */
  96. m = ilog10(val);
  97. if (m < 0) m = 0;
  98. if (m + prec + 3 >= SZB_OUTPUT) er = "OV"; /* Buffer overflow? */
  99. } else { /* E notation */
  100. if (val != 0) { /* Not a true zero? */
  101. val += i10x(ilog10(val) - prec) / 2; /* Round (nearest) */
  102. e = ilog10(val);
  103. if (e > 99 || prec + 6 >= SZB_OUTPUT) { /* Buffer overflow or E > +99? */
  104. er = "OV";
  105. } else {
  106. if (e < -99) e = -99;
  107. val /= i10x(e); /* Normalize */
  108. }
  109. }
  110. }
  111. }
  112. if (!er) { /* Not error condition */
  113. if (sign == '-') *buf++ = sign; /* Add a - if negative value */
  114. do { /* Put decimal number */
  115. w = i10x(m); /* Snip the highest digit d */
  116. d = val / w; val -= d * w;
  117. if (m == -1) *buf++ = XF_DPC; /* Insert a decimal separarot if get into fractional part */
  118. *buf++ = '0' + d; /* Put the digit */
  119. } while (--m >= -prec); /* Output all digits specified by prec */
  120. if (fmt != 'f') { /* Put exponent if needed */
  121. *buf++ = fmt;
  122. if (e < 0) {
  123. e = -e; *buf++ = '-';
  124. } else {
  125. *buf++ = '+';
  126. }
  127. *buf++ = '0' + e / 10;
  128. *buf++ = '0' + e % 10;
  129. }
  130. }
  131. }
  132. if (er) { /* Error condition? */
  133. if (sign) *buf++ = sign; /* Add sign if needed */
  134. do *buf++ = *er++; while (*er); /* Put error symbol */
  135. }
  136. *buf = 0; /* Term */
  137. }
  138. #endif /* XF_USE_FLOAT */
  139. /*----------------------------------------------*/
  140. /* Put a character */
  141. /*----------------------------------------------*/
  142. void xputc (
  143. int chr /* Character to be output */
  144. )
  145. {
  146. xfputc(xfunc_output, chr); /* Output it to the default output device */
  147. }
  148. void xfputc ( /* Put a character to the specified device */
  149. void(*func)(int), /* Pointer to the output function (null:strptr) */
  150. int chr /* Character to be output */
  151. )
  152. {
  153. if (XF_CRLF && chr == '\n') xfputc(func, '\r'); /* CR -> CRLF */
  154. if (func) {
  155. func(chr); /* Write a character to the output device */
  156. } else if (strptr) {
  157. *strptr++ = chr; /* Write a character to the memory */
  158. }
  159. }
  160. /*----------------------------------------------*/
  161. /* Put a null-terminated string */
  162. /*----------------------------------------------*/
  163. void xputs ( /* Put a string to the default device */
  164. const char* str /* Pointer to the string */
  165. )
  166. {
  167. xfputs(xfunc_output, str);
  168. }
  169. void xfputs ( /* Put a string to the specified device */
  170. void(*func)(int), /* Pointer to the output function */
  171. const char* str /* Pointer to the string */
  172. )
  173. {
  174. while (*str) { /* Put the string */
  175. xfputc(func, *str++);
  176. }
  177. }
  178. void xputs_P ( /* Put a string to the default device */
  179. const __flash char *str /* Pointer to the string */
  180. )
  181. {
  182. xfputs_P(xfunc_output, str);
  183. }
  184. void xfputs_P ( /* Put a string to the specified device */
  185. void(*func)(int), /* Pointer to the output function */
  186. const __flash char* str /* Pointer to the string */
  187. )
  188. {
  189. char c;
  190. while ((c = *str++)) { /* Put the string */
  191. xfputc(func, c);
  192. }
  193. }
  194. /*----------------------------------------------*/
  195. /* Formatted string output */
  196. /*----------------------------------------------*/
  197. /* xprintf("%d", 1234); "1234"
  198. xprintf("%6d,%3d%%", -200, 5); " -200, 5%"
  199. xprintf("%-6u", 100); "100 "
  200. xprintf("%ld", 12345678); "12345678"
  201. xprintf("%llu", 0x100000000); "4294967296" <XF_USE_LLI>
  202. xprintf("%lld", -1LL); "-1" <XF_USE_LLI>
  203. xprintf("%04x", 0xA3); "00a3"
  204. xprintf("%08lX", 0x123ABC); "00123ABC"
  205. xprintf("%016b", 0x550F); "0101010100001111"
  206. xprintf("%*d", 6, 100); " 100"
  207. xprintf("%s", "String"); "String"
  208. xprintf("%5s", "abc"); " abc"
  209. xprintf("%-5s", "abc"); "abc "
  210. xprintf("%-5s", "abcdefg"); "abcdefg"
  211. xprintf("%-5.5s", "abcdefg"); "abcde"
  212. xprintf("%-.5s", "abcdefg"); "abcde"
  213. xprintf("%-5.5s", "abc"); "abc "
  214. xprintf("%c", 'a'); "a"
  215. xprintf("%12f", 10.0); " 10.000000" <XF_USE_FP>
  216. xprintf("%.4E", 123.45678); "1.2346E+02" <XF_USE_FP>
  217. */
  218. static void xvfprintf (
  219. void(*func)(int), /* Pointer to the output function */
  220. const __flash char* fmt, /* Pointer to the format string */
  221. va_list arp /* Pointer to arguments */
  222. )
  223. {
  224. unsigned int r, i, j, w, f;
  225. int n, prec;
  226. char str[SZB_OUTPUT], c, d, *p, pad;
  227. #if XF_USE_LLI
  228. long long v;
  229. unsigned long long uv;
  230. #else
  231. long v;
  232. unsigned long uv;
  233. #endif
  234. for (;;) {
  235. c = *fmt++; /* Get a format character */
  236. if (!c) break; /* End of format? */
  237. if (c != '%') { /* Pass it through if not a % sequense */
  238. xfputc(func, c); continue;
  239. }
  240. f = w = 0; /* Clear parms */
  241. pad = ' '; prec = -1;
  242. c = *fmt++; /* Get first char of the sequense */
  243. if (c == '0') { /* Flag: left '0' padded */
  244. pad = '0'; c = *fmt++;
  245. } else {
  246. if (c == '-') { /* Flag: left justified */
  247. f = 2; c = *fmt++;
  248. }
  249. }
  250. if (c == '*') { /* Minimum width from an argument */
  251. n = va_arg(arp, int);
  252. if (n < 0) { /* Flag: left justified */
  253. n = 0 - n; f = 2;
  254. }
  255. w = n; c = *fmt++;
  256. } else {
  257. while (c >= '0' && c <= '9') { /* Minimum width */
  258. w = w * 10 + c - '0';
  259. c = *fmt++;
  260. }
  261. }
  262. if (c == '.') { /* Precision */
  263. c = *fmt++;
  264. if (c == '*') { /* Precision from an argument */
  265. prec = va_arg(arp, int);
  266. c = *fmt++;
  267. } else {
  268. prec = 0;
  269. while (c >= '0' && c <= '9') {
  270. prec = prec * 10 + c - '0';
  271. c = *fmt++;
  272. }
  273. }
  274. }
  275. if (c == 'l') { /* Prefix: Size is long */
  276. f |= 4; c = *fmt++;
  277. #if XF_USE_LLI
  278. if (c == 'l') { /* Prefix: Size is long long */
  279. f |= 8; c = *fmt++;
  280. }
  281. #endif
  282. }
  283. if (!c) break; /* End of format? */
  284. switch (c) { /* Type is... */
  285. case 'b': /* Unsigned binary */
  286. r = 2; break;
  287. case 'o': /* Unsigned octal */
  288. r = 8; break;
  289. case 'd': /* Signed decimal */
  290. case 'u': /* Unsigned decimal */
  291. r = 10; break;
  292. case 'x': /* Hexdecimal (lower case) */
  293. case 'X': /* Hexdecimal (upper case) */
  294. r = 16; break;
  295. case 'c': /* A character */
  296. xfputc(func, (char)va_arg(arp, int)); continue;
  297. case 's': /* String */
  298. p = va_arg(arp, char*); /* Get a pointer argument */
  299. if (!p) p = ""; /* Null ptr generates a null string */
  300. j = strlen(p);
  301. if (prec >= 0 && j > (unsigned int)prec) j = prec; /* Limited length of string body */
  302. for ( ; !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  303. while (*p && prec--) xfputc(func, *p++);/* String body */
  304. while (j++ < w) xfputc(func, ' '); /* Right pads */
  305. continue;
  306. #if XF_USE_FP
  307. case 'f': /* Float (decimal) */
  308. case 'e': /* Float (e) */
  309. case 'E': /* Float (E) */
  310. ftoa(p = str, va_arg(arp, double), prec, c); /* Make fp string */
  311. for (j = strlen(p); !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  312. while (*p) xfputc(func, *p++); /* Value */
  313. while (j++ < w) xfputc(func, ' '); /* Right pads */
  314. continue;
  315. #endif
  316. default: /* Unknown type (passthrough) */
  317. xfputc(func, c); continue;
  318. }
  319. /* Get an integer argument and put it in numeral */
  320. #if XF_USE_LLI
  321. if (f & 8) { /* long long argument? */
  322. v = (long long)va_arg(arp, long long);
  323. } else {
  324. if (f & 4) { /* long argument? */
  325. v = (c == 'd') ? (long long)va_arg(arp, long) : (long long)va_arg(arp, unsigned long);
  326. } else { /* int/short/char argument */
  327. v = (c == 'd') ? (long long)va_arg(arp, int) : (long long)va_arg(arp, unsigned int);
  328. }
  329. }
  330. #else
  331. if (f & 4) { /* long argument? */
  332. v = (long)va_arg(arp, long);
  333. } else { /* int/short/char argument */
  334. v = (c == 'd') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int);
  335. }
  336. #endif
  337. if (c == 'd' && v < 0) { /* Negative value? */
  338. v = 0 - v; f |= 1;
  339. }
  340. i = 0; uv = v;
  341. do { /* Make an integer number string */
  342. d = (char)(uv % r); uv /= r;
  343. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  344. str[i++] = d + '0';
  345. } while (uv != 0 && i < sizeof str);
  346. if (f & 1) str[i++] = '-'; /* Sign */
  347. for (j = i; !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  348. do xfputc(func, str[--i]); while (i != 0); /* Value */
  349. while (j++ < w) xfputc(func, ' '); /* Right pads */
  350. }
  351. }
  352. void xprintf ( /* Put a formatted string to the default device */
  353. const char* fmt, /* Pointer to the format string */
  354. ... /* Optional arguments */
  355. )
  356. {
  357. va_list arp;
  358. va_start(arp, fmt);
  359. xvfprintf(xfunc_output, fmt, arp);
  360. va_end(arp);
  361. }
  362. void xfprintf ( /* Put a formatted string to the specified device */
  363. void(*func)(int), /* Pointer to the output function */
  364. const char* fmt, /* Pointer to the format string */
  365. ... /* Optional arguments */
  366. )
  367. {
  368. va_list arp;
  369. va_start(arp, fmt);
  370. xvfprintf(func, fmt, arp);
  371. va_end(arp);
  372. }
  373. void xsprintf ( /* Put a formatted string to the memory */
  374. char* buff, /* Pointer to the output buffer */
  375. const char* fmt, /* Pointer to the format string */
  376. ... /* Optional arguments */
  377. )
  378. {
  379. va_list arp;
  380. strptr = buff; /* Enable destination for memory */
  381. va_start(arp, fmt);
  382. xvfprintf(0, fmt, arp);
  383. va_end(arp);
  384. *strptr = 0; /* Terminate output string */
  385. strptr = 0; /* Disable destination for memory */
  386. }
  387. #if XF_USE_DUMP
  388. /*----------------------------------------------*/
  389. /* Dump a line of binary dump */
  390. /*----------------------------------------------*/
  391. void put_dump (
  392. const void* buff, /* Pointer to the array to be dumped */
  393. unsigned long addr, /* Heading address value */
  394. int len, /* Number of items to be dumped */
  395. size_t width /* Size of buff[0] (1, 2 or 4) */
  396. )
  397. {
  398. int i;
  399. const unsigned char *bp;
  400. const unsigned short *sp;
  401. const unsigned long *lp;
  402. xprintf("%08lX ", addr); /* address */
  403. switch (width) {
  404. case sizeof (char):
  405. bp = buff;
  406. for (i = 0; i < len; i++) { /* Hexdecimal dump in (char) */
  407. xprintf(" %02X", bp[i]);
  408. }
  409. xputs(" ");
  410. for (i = 0; i < len; i++) { /* ASCII dump */
  411. xputc((unsigned char)((bp[i] >= ' ' && bp[i] <= '~') ? bp[i] : '.'));
  412. }
  413. break;
  414. case sizeof (short):
  415. sp = buff;
  416. do { /* Hexdecimal dump in (short) */
  417. xprintf(" %04X", *sp++);
  418. } while (--len);
  419. break;
  420. case sizeof (long):
  421. lp = buff;
  422. do { /* Hexdecimal dump in (short) */
  423. xprintf(" %08lX", *lp++);
  424. } while (--len);
  425. break;
  426. }
  427. xputc('\n');
  428. }
  429. #endif /* XF_USE_DUMP */
  430. #endif /* XF_USE_OUTPUT */
  431. #if XF_USE_INPUT
  432. int (*xfunc_input)(void); /* Pointer to the default input stream */
  433. /*----------------------------------------------*/
  434. /* Get a line from the input */
  435. /*----------------------------------------------*/
  436. int xgets ( /* 0:End of stream, 1:A line arrived */
  437. char* buff, /* Pointer to the buffer */
  438. int len /* Buffer length */
  439. )
  440. {
  441. int c, i;
  442. if (!xfunc_input) return 0; /* No input function is specified */
  443. i = 0;
  444. for (;;) {
  445. c = xfunc_input(); /* Get a char from the incoming stream */
  446. if (c < 0 || c == '\r') break; /* End of stream or CR? */
  447. if (c == '\b' && i) { /* BS? */
  448. i--;
  449. if (XF_INPUT_ECHO) xputc(c);
  450. continue;
  451. }
  452. if (c >= ' ' && i < len - 1) { /* Visible chars? */
  453. buff[i++] = c;
  454. if (XF_INPUT_ECHO) xputc(c);
  455. }
  456. }
  457. if (XF_INPUT_ECHO) {
  458. xputc('\r');
  459. xputc('\n');
  460. }
  461. buff[i] = 0; /* Terminate with a \0 */
  462. return (int)(c == '\r');
  463. }
  464. /*----------------------------------------------*/
  465. /* Get a value of integer string */
  466. /*----------------------------------------------*/
  467. /* "123 -5 0x3ff 0b1111 0377 w "
  468. ^ 1st call returns 123 and next ptr
  469. ^ 2nd call returns -5 and next ptr
  470. ^ 3rd call returns 1023 and next ptr
  471. ^ 4th call returns 15 and next ptr
  472. ^ 5th call returns 255 and next ptr
  473. ^ 6th call fails and returns 0
  474. */
  475. int xatoi ( /* 0:Failed, 1:Successful */
  476. char **str, /* Pointer to pointer to the string */
  477. long *res /* Pointer to the valiable to store the value */
  478. )
  479. {
  480. unsigned long val;
  481. unsigned char c, r, s = 0;
  482. *res = 0;
  483. while ((c = **str) == ' ') (*str)++; /* Skip leading spaces */
  484. if (c == '-') { /* negative? */
  485. s = 1;
  486. c = *(++(*str));
  487. }
  488. if (c == '0') {
  489. c = *(++(*str));
  490. switch (c) {
  491. case 'x': /* hexdecimal */
  492. r = 16; c = *(++(*str));
  493. break;
  494. case 'b': /* binary */
  495. r = 2; c = *(++(*str));
  496. break;
  497. default:
  498. if (c <= ' ') return 1; /* single zero */
  499. if (c < '0' || c > '9') return 0; /* invalid char */
  500. r = 8; /* octal */
  501. }
  502. } else {
  503. if (c < '0' || c > '9') return 0; /* EOL or invalid char */
  504. r = 10; /* decimal */
  505. }
  506. val = 0;
  507. while (c > ' ') {
  508. if (c >= 'a') c -= 0x20;
  509. c -= '0';
  510. if (c >= 17) {
  511. c -= 7;
  512. if (c <= 9) return 0; /* invalid char */
  513. }
  514. if (c >= r) return 0; /* invalid char for current radix */
  515. val = val * r + c;
  516. c = *(++(*str));
  517. }
  518. if (s) val = 0 - val; /* apply sign if needed */
  519. *res = val;
  520. return 1;
  521. }
  522. #if XF_USE_FP
  523. /*----------------------------------------------*/
  524. /* Get a value of the real number string */
  525. /*----------------------------------------------*/
  526. /* Float version of xatoi
  527. */
  528. int xatof ( /* 0:Failed, 1:Successful */
  529. char **str, /* Pointer to pointer to the string */
  530. double *res /* Pointer to the valiable to store the value */
  531. )
  532. {
  533. double val;
  534. int s, f, e;
  535. unsigned char c;
  536. *res = 0;
  537. s = f = 0;
  538. while ((c = **str) == ' ') (*str)++; /* Skip leading spaces */
  539. if (c == '-') { /* Negative? */
  540. c = *(++(*str)); s = 1;
  541. } else if (c == '+') { /* Positive? */
  542. c = *(++(*str));
  543. }
  544. if (c == XF_DPC) { /* Leading dp? */
  545. f = -1; /* Start at fractional part */
  546. c = *(++(*str));
  547. }
  548. if (c <= ' ') return 0; /* Wrong termination? */
  549. val = 0;
  550. while (c > ' ') { /* Get a value of decimal */
  551. if (c == XF_DPC) { /* Embedded dp? */
  552. if (f < 0) return 0; /* Wrong dp? */
  553. f = -1; /* Enter fractional part */
  554. } else {
  555. if (c < '0' || c > '9') break; /* End of decimal? */
  556. c -= '0';
  557. if (f == 0) { /* In integer part */
  558. val = val * 10 + c;
  559. } else { /* In fractional part */
  560. val += i10x(f--) * c;
  561. }
  562. }
  563. c = *(++(*str));
  564. }
  565. if (c > ' ') { /* It may be an exponent */
  566. if (c != 'e' && c != 'E') return 0; /* Wrong character? */
  567. c = *(++(*str));
  568. if (c == '-') {
  569. c = *(++(*str)); s |= 2; /* Negative exponent */
  570. } else if (c == '+') {
  571. c = *(++(*str)); /* Positive exponent */
  572. }
  573. if (c <= ' ') return 0; /* Wrong termination? */
  574. e = 0;
  575. while (c > ' ') { /* Get value of exponent */
  576. c -= '0';
  577. if (c > 9) return 0; /* Not a numeral? */
  578. e = e * 10 + c;
  579. c = *(++(*str));
  580. }
  581. val *= i10x((s & 2) ? -e : e); /* Apply exponent */
  582. }
  583. if (s & 1) val = -val; /* Negate sign if needed */
  584. *res = val;
  585. return 1;
  586. }
  587. #endif /* XF_USE_FP */
  588. #endif /* XF_USE_INPUT */