4-variable-simplifier/get_cached_simplifications.c

172 lines
3.3 KiB
C

#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <assert.h>
#include <defines.h>
#include <debug.h>
#include <cmdln.h>
#include "get_cached_simplifications.h"
#include "calculate_simplifications.h"
static struct path { char data[PATH_MAX]; } get_path(
const struct cmdln_flags* flags)
{
struct path path = {};
strcat(path.data, ".simplifier-cache-1");
if (flags->use_operators.not)
strcat(path.data, "-not");
if (flags->use_operators.or)
strcat(path.data, "-or");
if (flags->use_operators.orn)
strcat(path.data, "-orn");
if (flags->use_operators.nor)
strcat(path.data, "-nor");
if (flags->use_operators.and)
strcat(path.data, "-and");
if (flags->use_operators.andn)
strcat(path.data, "-andn");
if (flags->use_operators.nand)
strcat(path.data, "-nand");
if (flags->use_operators.xor)
strcat(path.data, "-xor");
if (flags->use_operators.nxor)
strcat(path.data, "-nxor");
if (flags->use_operators.lt)
strcat(path.data, "-lt");
if (flags->use_operators.lte)
strcat(path.data, "-lte");
if (flags->use_operators.gt)
strcat(path.data, "-gt");
if (flags->use_operators.gte)
strcat(path.data, "-gte");
if (flags->use_operators.ternary)
strcat(path.data, "-ternary");
strcat(path.data, ".bin");
return path;
}
struct simplifications get_cached_simplifications(
const struct cmdln_flags* flags)
{
struct path path = get_path(flags);
int fd = -1;
bool rebuild = flags->force_rebuild;
struct simplifications simps = {};
if (!rebuild)
{
fd = open(path.data, O_RDONLY);
if (fd > 0)
{
// great, just read it into memory
if (read(fd, &simps, sizeof(simps)) < (ssize_t) sizeof(simps))
{
printf("%s: read() to cache failed: %m\n", flags->argv0);
exit(1);
}
}
else if (errno == ENOENT)
{
rebuild = true;
}
else
{
TODO;
exit(1);
}
}
if (rebuild)
{
if (!flags->quiet)
{
puts(""
"I'll have to build up my cache of simplifications" "\n"
"I'll only have to do this once." "\n"
"\n"
"This may take a while." "\n"
"");
}
if (!flags->quiet && !flags->verbose)
{
puts("Re-run with '-v' to watch progress");
}
if (!flags->quiet && !flags->assume_yes)
{
puts("");
puts("Any input to start:"), getchar();
puts("Started.");
}
simps = calculate_simplifications(flags);
fd = open(path.data, O_WRONLY | O_TRUNC | O_CREAT, 0664);
if (fd < 0)
{
TODO;
exit(1);
}
if (write(fd, &simps, sizeof(simps)) < (ssize_t) sizeof(simps))
{
printf("%s: write() to cache failed: %m\n", flags->argv0);
exit(1);
}
}
if (fd > 0)
{
close(fd);
}
return simps;
}