xprintf.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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 = PSTR("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 = PSTR("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 = PSTR("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 = PSTR("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. char ec = pgm_read_byte(er);
  135. do {
  136. *buf++ = ec;
  137. ec = pgm_read_byte(++er);
  138. } while (ec); /* Put error symbol */
  139. }
  140. *buf = 0; /* Term */
  141. }
  142. #endif /* XF_USE_FLOAT */
  143. /*----------------------------------------------*/
  144. /* Put a character */
  145. /*----------------------------------------------*/
  146. void xputc (
  147. int chr /* Character to be output */
  148. )
  149. {
  150. xfputc(xfunc_output, chr); /* Output it to the default output device */
  151. }
  152. void xfputc ( /* Put a character to the specified device */
  153. void(*func)(int), /* Pointer to the output function (null:strptr) */
  154. int chr /* Character to be output */
  155. )
  156. {
  157. if (XF_CRLF && chr == '\n') xfputc(func, '\r'); /* CR -> CRLF */
  158. if (func) {
  159. func(chr); /* Write a character to the output device */
  160. } else if (strptr) {
  161. *strptr++ = chr; /* Write a character to the memory */
  162. }
  163. }
  164. /*----------------------------------------------*/
  165. /* Put a null-terminated string */
  166. /*----------------------------------------------*/
  167. void xputs ( /* Put a string to the default device */
  168. const char* str /* Pointer to the string */
  169. )
  170. {
  171. xfputs(xfunc_output, str);
  172. }
  173. void xfputs ( /* Put a string to the specified device */
  174. void(*func)(int), /* Pointer to the output function */
  175. const char* str /* Pointer to the string */
  176. )
  177. {
  178. while (*str) { /* Put the string */
  179. xfputc(func, *str++);
  180. }
  181. }
  182. void xputs_P ( /* Put a string to the default device */
  183. const __flash char *str /* Pointer to the string */
  184. )
  185. {
  186. xfputs_P(xfunc_output, str);
  187. }
  188. void xfputs_P ( /* Put a string to the specified device */
  189. void(*func)(int), /* Pointer to the output function */
  190. const __flash char* str /* Pointer to the string */
  191. )
  192. {
  193. char c;
  194. while ((c = *str++)) { /* Put the string */
  195. xfputc(func, c);
  196. }
  197. }
  198. /*----------------------------------------------*/
  199. /* Formatted string output */
  200. /*----------------------------------------------*/
  201. /* xprintf("%d", 1234); "1234"
  202. xprintf("%6d,%3d%%", -200, 5); " -200, 5%"
  203. xprintf("%-6u", 100); "100 "
  204. xprintf("%ld", 12345678); "12345678"
  205. xprintf("%llu", 0x100000000); "4294967296" <XF_USE_LLI>
  206. xprintf("%lld", -1LL); "-1" <XF_USE_LLI>
  207. xprintf("%04x", 0xA3); "00a3"
  208. xprintf("%08lX", 0x123ABC); "00123ABC"
  209. xprintf("%016b", 0x550F); "0101010100001111"
  210. xprintf("%*d", 6, 100); " 100"
  211. xprintf("%s", "String"); "String"
  212. xprintf("%5s", "abc"); " abc"
  213. xprintf("%-5s", "abc"); "abc "
  214. xprintf("%-5s", "abcdefg"); "abcdefg"
  215. xprintf("%-5.5s", "abcdefg"); "abcde"
  216. xprintf("%-.5s", "abcdefg"); "abcde"
  217. xprintf("%-5.5s", "abc"); "abc "
  218. xprintf("%c", 'a'); "a"
  219. xprintf("%12f", 10.0); " 10.000000" <XF_USE_FP>
  220. xprintf("%.4E", 123.45678); "1.2346E+02" <XF_USE_FP>
  221. */
  222. static void xvfprintf (
  223. void(*func)(int), /* Pointer to the output function */
  224. const __flash char* fmt, /* Pointer to the format string */
  225. va_list arp /* Pointer to arguments */
  226. )
  227. {
  228. unsigned int r, i, j, w, f;
  229. int n, prec;
  230. char str[SZB_OUTPUT], c, d, *p, pad;
  231. #if XF_USE_LLI
  232. long long v;
  233. unsigned long long uv;
  234. #else
  235. long v;
  236. unsigned long uv;
  237. #endif
  238. for (;;) {
  239. c = *fmt++; /* Get a format character */
  240. if (!c) break; /* End of format? */
  241. if (c != '%') { /* Pass it through if not a % sequense */
  242. xfputc(func, c); continue;
  243. }
  244. f = w = 0; /* Clear parms */
  245. pad = ' '; prec = -1;
  246. c = *fmt++; /* Get first char of the sequense */
  247. if (c == '0') { /* Flag: left '0' padded */
  248. pad = '0'; c = *fmt++;
  249. } else {
  250. if (c == '-') { /* Flag: left justified */
  251. f = 2; c = *fmt++;
  252. }
  253. }
  254. if (c == '*') { /* Minimum width from an argument */
  255. n = va_arg(arp, int);
  256. if (n < 0) { /* Flag: left justified */
  257. n = 0 - n; f = 2;
  258. }
  259. w = n; c = *fmt++;
  260. } else {
  261. while (c >= '0' && c <= '9') { /* Minimum width */
  262. w = w * 10 + c - '0';
  263. c = *fmt++;
  264. }
  265. }
  266. if (c == '.') { /* Precision */
  267. c = *fmt++;
  268. if (c == '*') { /* Precision from an argument */
  269. prec = va_arg(arp, int);
  270. c = *fmt++;
  271. } else {
  272. prec = 0;
  273. while (c >= '0' && c <= '9') {
  274. prec = prec * 10 + c - '0';
  275. c = *fmt++;
  276. }
  277. }
  278. }
  279. if (c == 'l') { /* Prefix: Size is long */
  280. f |= 4; c = *fmt++;
  281. #if XF_USE_LLI
  282. if (c == 'l') { /* Prefix: Size is long long */
  283. f |= 8; c = *fmt++;
  284. }
  285. #endif
  286. }
  287. if (!c) break; /* End of format? */
  288. switch (c) { /* Type is... */
  289. case 'b': /* Unsigned binary */
  290. r = 2; break;
  291. case 'o': /* Unsigned octal */
  292. r = 8; break;
  293. case 'd': /* Signed decimal */
  294. case 'u': /* Unsigned decimal */
  295. r = 10; break;
  296. case 'x': /* Hexdecimal (lower case) */
  297. case 'X': /* Hexdecimal (upper case) */
  298. r = 16; break;
  299. case 'c': /* A character */
  300. xfputc(func, (char)va_arg(arp, int)); continue;
  301. case 's': /* String */
  302. p = va_arg(arp, char*); /* Get a pointer argument */
  303. if (!p) p = ""; /* Null ptr generates a null string */
  304. j = strlen(p);
  305. if (prec >= 0 && j > (unsigned int)prec) j = prec; /* Limited length of string body */
  306. for ( ; !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  307. while (*p && prec--) xfputc(func, *p++);/* String body */
  308. while (j++ < w) xfputc(func, ' '); /* Right pads */
  309. continue;
  310. #if XF_USE_FP
  311. case 'f': /* Float (decimal) */
  312. case 'e': /* Float (e) */
  313. case 'E': /* Float (E) */
  314. ftoa(p = str, va_arg(arp, double), prec, c); /* Make fp string */
  315. for (j = strlen(p); !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  316. while (*p) xfputc(func, *p++); /* Value */
  317. while (j++ < w) xfputc(func, ' '); /* Right pads */
  318. continue;
  319. #endif
  320. default: /* Unknown type (passthrough) */
  321. xfputc(func, c); continue;
  322. }
  323. /* Get an integer argument and put it in numeral */
  324. #if XF_USE_LLI
  325. if (f & 8) { /* long long argument? */
  326. v = (long long)va_arg(arp, long long);
  327. } else {
  328. if (f & 4) { /* long argument? */
  329. v = (c == 'd') ? (long long)va_arg(arp, long) : (long long)va_arg(arp, unsigned long);
  330. } else { /* int/short/char argument */
  331. v = (c == 'd') ? (long long)va_arg(arp, int) : (long long)va_arg(arp, unsigned int);
  332. }
  333. }
  334. #else
  335. if (f & 4) { /* long argument? */
  336. v = (long)va_arg(arp, long);
  337. } else { /* int/short/char argument */
  338. v = (c == 'd') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int);
  339. }
  340. #endif
  341. if (c == 'd' && v < 0) { /* Negative value? */
  342. v = 0 - v; f |= 1;
  343. }
  344. i = 0; uv = v;
  345. do { /* Make an integer number string */
  346. d = (char)(uv % r); uv /= r;
  347. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  348. str[i++] = d + '0';
  349. } while (uv != 0 && i < sizeof str);
  350. if (f & 1) str[i++] = '-'; /* Sign */
  351. for (j = i; !(f & 2) && j < w; j++) xfputc(func, pad); /* Left pads */
  352. do xfputc(func, str[--i]); while (i != 0); /* Value */
  353. while (j++ < w) xfputc(func, ' '); /* Right pads */
  354. }
  355. }
  356. void xprintf ( /* Put a formatted string to the default device */
  357. const char* fmt, /* Pointer to the format string */
  358. ... /* Optional arguments */
  359. )
  360. {
  361. va_list arp;
  362. va_start(arp, fmt);
  363. xvfprintf(xfunc_output, fmt, arp);
  364. va_end(arp);
  365. }
  366. void xfprintf ( /* Put a formatted string to the specified device */
  367. void(*func)(int), /* Pointer to the output function */
  368. const char* fmt, /* Pointer to the format string */
  369. ... /* Optional arguments */
  370. )
  371. {
  372. va_list arp;
  373. va_start(arp, fmt);
  374. xvfprintf(func, fmt, arp);
  375. va_end(arp);
  376. }
  377. void xsprintf ( /* Put a formatted string to the memory */
  378. char* buff, /* Pointer to the output buffer */
  379. const char* fmt, /* Pointer to the format string */
  380. ... /* Optional arguments */
  381. )
  382. {
  383. va_list arp;
  384. strptr = buff; /* Enable destination for memory */
  385. va_start(arp, fmt);
  386. xvfprintf(0, fmt, arp);
  387. va_end(arp);
  388. *strptr = 0; /* Terminate output string */
  389. strptr = 0; /* Disable destination for memory */
  390. }
  391. #if XF_USE_DUMP
  392. /*----------------------------------------------*/
  393. /* Dump a line of binary dump */
  394. /*----------------------------------------------*/
  395. void put_dump (
  396. const void* buff, /* Pointer to the array to be dumped */
  397. unsigned long addr, /* Heading address value */
  398. int len, /* Number of items to be dumped */
  399. size_t width /* Size of buff[0] (1, 2 or 4) */
  400. )
  401. {
  402. int i;
  403. const unsigned char *bp;
  404. const unsigned short *sp;
  405. const unsigned long *lp;
  406. xprintf(PSTR("%08lX "), addr); /* address */
  407. switch (width) {
  408. case sizeof (char):
  409. bp = buff;
  410. for (i = 0; i < len; i++) { /* Hexdecimal dump in (char) */
  411. xprintf(PSTR(" %02X"), bp[i]);
  412. }
  413. xputs_P(PSTR(" "));
  414. for (i = 0; i < len; i++) { /* ASCII dump */
  415. xputc((unsigned char)((bp[i] >= ' ' && bp[i] <= '~') ? bp[i] : '.'));
  416. }
  417. break;
  418. case sizeof (short):
  419. sp = buff;
  420. do { /* Hexdecimal dump in (short) */
  421. xprintf(PSTR(" %04X"), *sp++);
  422. } while (--len);
  423. break;
  424. case sizeof (long):
  425. lp = buff;
  426. do { /* Hexdecimal dump in (short) */
  427. xprintf(PSTR(" %08lX"), *lp++);
  428. } while (--len);
  429. break;
  430. }
  431. xputc('\n');
  432. }
  433. #endif /* XF_USE_DUMP */
  434. #endif /* XF_USE_OUTPUT */
  435. #if XF_USE_INPUT
  436. int (*xfunc_input)(void); /* Pointer to the default input stream */
  437. /*----------------------------------------------*/
  438. /* Get a line from the input */
  439. /*----------------------------------------------*/
  440. int xgets ( /* 0:End of stream, 1:A line arrived */
  441. char* buff, /* Pointer to the buffer */
  442. int len /* Buffer length */
  443. )
  444. {
  445. int c, i;
  446. if (!xfunc_input) return 0; /* No input function is specified */
  447. i = 0;
  448. for (;;) {
  449. c = xfunc_input(); /* Get a char from the incoming stream */
  450. if (c < 0 || c == '\r') break; /* End of stream or CR? */
  451. if (c == '\b' && i) { /* BS? */
  452. i--;
  453. if (XF_INPUT_ECHO) xputc(c);
  454. continue;
  455. }
  456. if (c >= ' ' && i < len - 1) { /* Visible chars? */
  457. buff[i++] = c;
  458. if (XF_INPUT_ECHO) xputc(c);
  459. }
  460. }
  461. if (XF_INPUT_ECHO) {
  462. xputc('\r');
  463. xputc('\n');
  464. }
  465. buff[i] = 0; /* Terminate with a \0 */
  466. return (int)(c == '\r');
  467. }
  468. /*----------------------------------------------*/
  469. /* Get a value of integer string */
  470. /*----------------------------------------------*/
  471. /* "123 -5 0x3ff 0b1111 0377 w "
  472. ^ 1st call returns 123 and next ptr
  473. ^ 2nd call returns -5 and next ptr
  474. ^ 3rd call returns 1023 and next ptr
  475. ^ 4th call returns 15 and next ptr
  476. ^ 5th call returns 255 and next ptr
  477. ^ 6th call fails and returns 0
  478. */
  479. int xatoi ( /* 0:Failed, 1:Successful */
  480. char **str, /* Pointer to pointer to the string */
  481. long *res /* Pointer to the valiable to store the value */
  482. )
  483. {
  484. unsigned long val;
  485. unsigned char c, r, s = 0;
  486. *res = 0;
  487. while ((c = **str) == ' ') (*str)++; /* Skip leading spaces */
  488. if (c == '-') { /* negative? */
  489. s = 1;
  490. c = *(++(*str));
  491. }
  492. if (c == '0') {
  493. c = *(++(*str));
  494. switch (c) {
  495. case 'x': /* hexdecimal */
  496. r = 16; c = *(++(*str));
  497. break;
  498. case 'b': /* binary */
  499. r = 2; c = *(++(*str));
  500. break;
  501. default:
  502. if (c <= ' ') return 1; /* single zero */
  503. if (c < '0' || c > '9') return 0; /* invalid char */
  504. r = 8; /* octal */
  505. }
  506. } else {
  507. if (c < '0' || c > '9') return 0; /* EOL or invalid char */
  508. r = 10; /* decimal */
  509. }
  510. val = 0;
  511. while (c > ' ') {
  512. if (c >= 'a') c -= 0x20;
  513. c -= '0';
  514. if (c >= 17) {
  515. c -= 7;
  516. if (c <= 9) return 0; /* invalid char */
  517. }
  518. if (c >= r) return 0; /* invalid char for current radix */
  519. val = val * r + c;
  520. c = *(++(*str));
  521. }
  522. if (s) val = 0 - val; /* apply sign if needed */
  523. *res = val;
  524. return 1;
  525. }
  526. #endif /* XF_USE_INPUT */
  527. #if XF_USE_FP
  528. /*----------------------------------------------*/
  529. /* Get a value of the real number string */
  530. /*----------------------------------------------*/
  531. /* Float version of xatoi
  532. */
  533. int xatof ( /* 0:Failed, 1:Successful */
  534. const char **str, /* Pointer to pointer to the string */
  535. double *res /* Pointer to the valiable to store the value */
  536. )
  537. {
  538. double val;
  539. int s, f, e;
  540. unsigned char c;
  541. *res = 0;
  542. s = f = 0;
  543. while ((c = **str) == ' ') (*str)++; /* Skip leading spaces */
  544. if (c == '-') { /* Negative? */
  545. c = *(++(*str)); s = 1;
  546. } else if (c == '+') { /* Positive? */
  547. c = *(++(*str));
  548. }
  549. if (c == XF_DPC) { /* Leading dp? */
  550. f = -1; /* Start at fractional part */
  551. c = *(++(*str));
  552. }
  553. if (c <= ' ') return 0; /* Wrong termination? */
  554. val = 0;
  555. while (c > ' ') { /* Get a value of decimal */
  556. if (c == XF_DPC) { /* Embedded dp? */
  557. if (f < 0) return 0; /* Wrong dp? */
  558. f = -1; /* Enter fractional part */
  559. } else {
  560. if (c < '0' || c > '9') break; /* End of decimal? */
  561. c -= '0';
  562. if (f == 0) { /* In integer part */
  563. val = val * 10 + c;
  564. } else { /* In fractional part */
  565. val += i10x(f--) * c;
  566. }
  567. }
  568. c = *(++(*str));
  569. }
  570. if (c > ' ') { /* It may be an exponent */
  571. if (c != 'e' && c != 'E') return 0; /* Wrong character? */
  572. c = *(++(*str));
  573. if (c == '-') {
  574. c = *(++(*str)); s |= 2; /* Negative exponent */
  575. } else if (c == '+') {
  576. c = *(++(*str)); /* Positive exponent */
  577. }
  578. if (c <= ' ') return 0; /* Wrong termination? */
  579. e = 0;
  580. while (c > ' ') { /* Get value of exponent */
  581. c -= '0';
  582. if (c > 9) return 0; /* Not a numeral? */
  583. e = e * 10 + c;
  584. c = *(++(*str));
  585. }
  586. val *= i10x((s & 2) ? -e : e); /* Apply exponent */
  587. }
  588. if (s & 1) val = -val; /* Negate sign if needed */
  589. *res = val;
  590. return 1;
  591. }
  592. #endif /* XF_USE_FP */