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.6KB

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