1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/files/block_file_accessor.cc Sun Mar 14 21:41:49 2021 +0100
1.3 @@ -0,0 +1,85 @@
1.4 +#include <stdio.h>
1.5 +#include <string.h>
1.6 +#include <sys/types.h>
1.7 +#include <sys/stat.h>
1.8 +
1.9 +#include <algorithm>
1.10 +
1.11 +#include "block_file_accessor.h"
1.12 +
1.13 +
1.14 +
1.15 +BlockFileAccessor::BlockFileAccessor(const char *path, fileid_t fileid)
1.16 +: Accessor(fileid)
1.17 +{
1.18 + /* Obtain the size of the file. */
1.19 +
1.20 + struct stat buf;
1.21 +
1.22 + if (stat(path, &buf))
1.23 + {
1.24 + _size = 0;
1.25 + return;
1.26 + }
1.27 +
1.28 + /* Allocate memory. */
1.29 +
1.30 + _size = buf.st_size;
1.31 + _data = (char *) malloc(_size);
1.32 +
1.33 + if (_data == NULL)
1.34 + return;
1.35 +
1.36 + /* Load the file into memory and initialise the size. */
1.37 +
1.38 + FILE *fp = fopen(path, "r");
1.39 +
1.40 + if (fp == NULL)
1.41 + {
1.42 + free(_data);
1.43 + return;
1.44 + }
1.45 +
1.46 + _size = fread(_data, sizeof(char), _size, fp);
1.47 +
1.48 + fclose(fp);
1.49 +}
1.50 +
1.51 +/* Data transfer methods. */
1.52 +
1.53 +void BlockFileAccessor::fill(Flexpage *flexpage)
1.54 +{
1.55 + offset_t filepos = flexpage->base_offset;
1.56 + offset_t addr = flexpage->base_addr;
1.57 + offset_t populated_size = std::min(flexpage->size, _size - filepos);
1.58 +
1.59 + /* Tag the region with file state. */
1.60 +
1.61 + flexpage->region->fill(fileid, filepos);
1.62 +
1.63 + /* Fill the region with file content. */
1.64 +
1.65 + memcpy((void *) addr, _data + filepos, populated_size);
1.66 +
1.67 + /* Pad the flexpage with zero. */
1.68 +
1.69 + if (populated_size < flexpage->size)
1.70 + memset((void *) (addr + populated_size), 0, flexpage->size - populated_size);
1.71 +}
1.72 +
1.73 +void BlockFileAccessor::flush(Flexpage *flexpage)
1.74 +{
1.75 + offset_t addr = flexpage->base_addr;
1.76 + offset_t filepos = flexpage->base_offset;
1.77 + offset_t populated_size = std::min(flexpage->size, _size - filepos);
1.78 +
1.79 + /* Remove the file state tag from the region. */
1.80 +
1.81 + flexpage->region->flush();
1.82 +
1.83 + /* Copy the populated region to the block memory. */
1.84 +
1.85 + memcpy((void *) (_data + filepos), (const void *) addr, populated_size);
1.86 +}
1.87 +
1.88 +// vim: tabstop=4 expandtab shiftwidth=4