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