| 5 | #include <string.h> /* memcpy */ |
| 6 | |
| 7 | void |
| 8 | WriteRecordToFile(RecordKind kind, uint8_t* data, size_t data_size, FILE* outfile) |
| 9 | { |
| 10 | uint8_t vlen[4], rlen[5]; |
| 11 | LenLenPair p = calculate_vlen_rlen_sizes(data_size, vlen, rlen); |
| 12 | size_t vlenlen = p.vlenlen; |
| 13 | size_t rlenlen = p.rlenlen; |
| 14 | |
| 15 | uint8_t magic = (uint8_t)kind | vlenlen_to_lenlen(vlenlen); |
| 16 | |
| 17 | size_t buf_size = sizeof(magic) + vlenlen + data_size + rlenlen; |
| 18 | // sizeof(magic) + vlenlen + rlenlen cannot wrap, |
| 19 | // so we only have to check for wrap on data_size |
| 20 | if (buf_size < data_size) { |
| 21 | LOG("data_size exceeds maximum record size"); |
| 22 | return; |
| 23 | } |
| 24 | uint8_t* buf = (uint8_t*)alloca(buf_size); |
| 25 | size_t cursor = 0; |
| 26 | |
| 27 | // cursor |
| 28 | // ↓ |
| 29 | // [magic][...] |
| 30 | buf[cursor] = magic; |
| 31 | cursor++; |
| 32 | |
| 33 | // cursor |
| 34 | // ↓ |
| 35 | // [magic][vlen][...] |
| 36 | memcpy(buf + cursor, vlen, vlenlen); |
| 37 | cursor += vlenlen; |
| 38 | |
| 39 | // cursor |
| 40 | // ↓ |
| 41 | // [magic][vlen][data][...] |
| 42 | //if (cursor > buf_size - 1 - vlenlen - data_size) return; |
| 43 | memcpy(buf + cursor, data, data_size); |
| 44 | cursor += data_size; |
| 45 | |
| 46 | // cursor |
| 47 | // ↓ |
| 48 | // [magic][vlen][data][rlen] |
| 49 | memcpy(buf + cursor, rlen, rlenlen); |
| 50 | |
| 51 | fwrite(buf, buf_size, 1, outfile); |
| 52 | } |
| 53 | |
| 54 | size_t |
| 55 | lenlen(uint8_t ty) |
no test coverage detected