ES-2024 reverter
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.2KB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include "linebuffer.h"
  6. struct linebuffer * create_linebuffer(int size)
  7. {
  8. struct linebuffer *retval = malloc(sizeof(struct linebuffer) + size);
  9. if (retval == NULL)
  10. return NULL;
  11. retval->size = size;
  12. retval->pos = 0;
  13. return retval;
  14. }
  15. int linebuffer_read(struct linebuffer *lbuf, int fd)
  16. {
  17. char buf[32];
  18. int len = read(fd, buf, sizeof(buf));
  19. if (len <= 0)
  20. return -1;
  21. int i;
  22. for (i = 0; i < len; i++) {
  23. /* "understand" backspace */
  24. if (buf[i] == 0x08 && lbuf->pos > 0) {
  25. lbuf->pos--;
  26. /* copy */
  27. } else if (buf[i] >= ' ' || buf[i] == '\r') {
  28. lbuf->data[lbuf->pos++] = buf[i];
  29. }
  30. if (lbuf->pos > lbuf->size)
  31. return -1;
  32. }
  33. return 0;
  34. }
  35. char * linebuffer_get(struct linebuffer *lbuf)
  36. {
  37. char *newline = memchr(lbuf->data, '\r', lbuf->pos);
  38. if (newline == NULL)
  39. return NULL;
  40. char *retval = NULL;
  41. *newline = '\0';
  42. int len = newline - lbuf->data;
  43. if (len > 0)
  44. retval = strdup(lbuf->data);
  45. lbuf->pos -= len +1;
  46. memmove(lbuf->data, newline +1, lbuf->pos);
  47. return retval;
  48. }
  49. int linebuffer_clear(struct linebuffer *lbuf)
  50. {
  51. int oldpos = lbuf->pos;
  52. lbuf->pos = 0;
  53. return oldpos;
  54. }