2 #include "chunk-format.h"
6 * When writing a chunk-based file format, collect the chunks in
7 * an array of chunk_info structs. The size stores the _expected_
8 * amount of data that will be written by write_fn.
13 chunk_write_fn write_fn;
19 struct chunk_info *chunks;
24 struct chunkfile *init_chunkfile(struct hashfile *f)
26 struct chunkfile *cf = xcalloc(1, sizeof(*cf));
31 void free_chunkfile(struct chunkfile *cf)
39 int get_num_chunks(struct chunkfile *cf)
44 void add_chunk(struct chunkfile *cf,
49 ALLOC_GROW(cf->chunks, cf->chunks_nr + 1, cf->chunks_alloc);
51 cf->chunks[cf->chunks_nr].id = id;
52 cf->chunks[cf->chunks_nr].write_fn = fn;
53 cf->chunks[cf->chunks_nr].size = size;
57 int write_chunkfile(struct chunkfile *cf, void *data)
60 uint64_t cur_offset = hashfile_total(cf->f);
62 /* Add the table of contents to the current offset */
63 cur_offset += (cf->chunks_nr + 1) * CHUNK_TOC_ENTRY_SIZE;
65 for (i = 0; i < cf->chunks_nr; i++) {
66 hashwrite_be32(cf->f, cf->chunks[i].id);
67 hashwrite_be64(cf->f, cur_offset);
69 cur_offset += cf->chunks[i].size;
72 /* Trailing entry marks the end of the chunks */
73 hashwrite_be32(cf->f, 0);
74 hashwrite_be64(cf->f, cur_offset);
76 for (i = 0; i < cf->chunks_nr; i++) {
77 off_t start_offset = hashfile_total(cf->f);
78 int result = cf->chunks[i].write_fn(cf->f, data);
83 if (hashfile_total(cf->f) - start_offset != cf->chunks[i].size)
84 BUG("expected to write %"PRId64" bytes to chunk %"PRIx32", but wrote %"PRId64" instead",
85 cf->chunks[i].size, cf->chunks[i].id,
86 hashfile_total(cf->f) - start_offset);