flakystream.c 906 B

123456789101112131415161718192021222324252627282930313233
  1. #include "flakystream.h"
  2. #include <string.h>
  3. bool flakystream_callback(pb_istream_t *stream, pb_byte_t *buf, size_t count)
  4. {
  5. flakystream_t *state = stream->state;
  6. if (state->position + count > state->msglen)
  7. {
  8. stream->bytes_left = 0;
  9. return false;
  10. }
  11. else if (state->position + count > state->fail_after)
  12. {
  13. PB_RETURN_ERROR(stream, "flaky error");
  14. }
  15. memcpy(buf, state->buffer + state->position, count);
  16. state->position += count;
  17. return true;
  18. }
  19. void flakystream_init(flakystream_t *stream, const uint8_t *buffer, size_t msglen, size_t fail_after)
  20. {
  21. memset(stream, 0, sizeof(*stream));
  22. stream->stream.callback = flakystream_callback;
  23. stream->stream.bytes_left = SIZE_MAX;
  24. stream->stream.state = stream;
  25. stream->buffer = buffer;
  26. stream->position = 0;
  27. stream->msglen = msglen;
  28. stream->fail_after = fail_after;
  29. }