ib_getw.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2003 Gunnar Ritter
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute
  10. * it freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. *
  17. * 2. Altered source versions must be plainly marked as such, and must not be
  18. * misrepresented as being the original software.
  19. *
  20. * 3. This notice may not be removed or altered from any source distribution.
  21. */
  22. /* Sccsid @(#)ib_getw.c 1.5 (gritter) 7/16/04 */
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include "iblok.h"
  26. #include "mbtowi.h"
  27. char *
  28. ib_getw(struct iblok *ip, wint_t *wc, int *len)
  29. {
  30. size_t rest;
  31. int c, i, n;
  32. i = 0;
  33. rest = ip->ib_mend - ip->ib_mcur;
  34. if (rest && ip->ib_mcur > ip->ib_mbuf) {
  35. do
  36. ip->ib_mbuf[i] = ip->ib_mcur[i];
  37. while (i++, --rest);
  38. } else if (ip->ib_incompl) {
  39. ip->ib_incompl = 0;
  40. *wc = WEOF;
  41. ip->ib_mend = ip->ib_mcur = NULL;
  42. return NULL;
  43. }
  44. if (i == 0) {
  45. c = ib_get(ip);
  46. if (c == EOF) {
  47. *wc = WEOF;
  48. ip->ib_mend = ip->ib_mcur = NULL;
  49. return NULL;
  50. }
  51. ip->ib_mbuf[i++] = (char)c;
  52. }
  53. if (ip->ib_mbuf[0] & 0200) {
  54. while (ip->ib_mbuf[i-1] != '\n' && i < ip->ib_mb_cur_max &&
  55. ip->ib_incompl == 0) {
  56. c = ib_get(ip);
  57. if (c != EOF)
  58. ip->ib_mbuf[i++] = (char)c;
  59. else
  60. ip->ib_incompl = 1;
  61. }
  62. n = mbtowi(wc, ip->ib_mbuf, i);
  63. if (n < 0) {
  64. *len = 1;
  65. *wc = WEOF;
  66. } else if (n == 0) {
  67. *len = 1;
  68. *wc = '\0';
  69. } else
  70. *len = n;
  71. } else {
  72. *wc = ip->ib_mbuf[0];
  73. *len = n = 1;
  74. }
  75. ip->ib_mcur = &ip->ib_mbuf[*len];
  76. ip->ib_mend = &ip->ib_mcur[i - *len];
  77. return ip->ib_mbuf;
  78. }