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.

io.c 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "io.h"
  2. #include <stdlib.h>
  3. void l2_bufio_reader_init(struct l2_bufio_reader *b, struct l2_io_reader *r) {
  4. b->r = r;
  5. b->len = 0;
  6. b->idx = 0;
  7. }
  8. void l2_bufio_shift(struct l2_bufio_reader *b) {
  9. if (b->idx > 0) {
  10. b->len -= b->idx;
  11. memmove(b->buf, b->buf + b->idx, b->len);
  12. }
  13. b->len += b->r->read(b->r, b->buf + b->len, sizeof(b->buf) - b->len);
  14. b->idx = 0;
  15. }
  16. int l2_bufio_shift_peek(struct l2_bufio_reader *b, size_t count) {
  17. size_t offset = count - 1;
  18. l2_bufio_shift(b);
  19. if (b->len <= offset) {
  20. return EOF;
  21. }
  22. return b->buf[offset];
  23. }
  24. int l2_bufio_shift_get(struct l2_bufio_reader *b) {
  25. l2_bufio_shift(b);
  26. if (b->len == 0) {
  27. return EOF;
  28. }
  29. return b->buf[b->idx++];
  30. }
  31. void l2_bufio_writer_init(struct l2_bufio_writer *b, struct l2_io_writer *w) {
  32. b->w = w;
  33. b->idx = 0;
  34. }
  35. void l2_bufio_flush(struct l2_bufio_writer *b) {
  36. b->w->write(b->w, b->buf, b->idx);
  37. b->idx = 0;
  38. }
  39. size_t l2_io_mem_read(struct l2_io_reader *self, char *buf, size_t len) {
  40. struct l2_io_mem_reader *r = (struct l2_io_mem_reader *)self;
  41. if (len >= r->len - r->idx) {
  42. len = r->len - r->idx;
  43. }
  44. memcpy(buf, r->mem + r->idx, len);
  45. r->idx += len;
  46. return len;
  47. }
  48. size_t l2_io_file_read(struct l2_io_reader *self, char *buf, size_t len) {
  49. struct l2_io_file_reader *r = (struct l2_io_file_reader *)self;
  50. return fread(buf, 1, len, r->f);
  51. }
  52. void l2_io_mem_write(struct l2_io_writer *self, const char *buf, size_t len) {
  53. struct l2_io_mem_writer *w = (struct l2_io_mem_writer *)self;
  54. size_t idx = w->len;
  55. w->len += len;
  56. w->mem = realloc(w->mem, w->len);
  57. memcpy(w->mem + idx, buf, len);
  58. }
  59. void l2_io_file_write(struct l2_io_writer *self, const char *buf, size_t len) {
  60. struct l2_io_file_writer *w = (struct l2_io_file_writer *)self;
  61. fwrite(buf, 1, len, w->f);
  62. }