#include "join.h"
#include "platform.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// Two sources, the newline that ends the first and the blank line, and one byte
// more to tell that a file is too long.
constexpr size_t BUF_SIZE = 2 * JOIN_SOURCE_MAX + 3;
static char built[BUF_SIZE];
static char current[BUF_SIZE];
// Read up to CAP bytes of PATH into BUF. Returns 0 or an errno value.
static int read_into(const char *path, char *buf, size_t cap, size_t *len)
{
*len = 0;
int fd = sys_open(path, O_RDONLY, 0);
if (fd < 0) return errno;
ssize_t n = 1;
while (*len < cap && n > 0) {
n = sys_read(fd, buf + *len, cap - *len);
if (n < 0 && errno == EINTR) {
n = 1;
continue;
}
*len += n > 0 ? (size_t)n : 0;
}
int err = n < 0 ? errno : 0;
(void)sys_close(fd);
return err;
}
// Append the source at PATH to BUILT, which holds *LEN bytes.
static int add_source(const char *path, size_t *len)
{
size_t n;
int err = read_into(path, built + *len, JOIN_SOURCE_MAX + 1, &n);
if (err == 0 && n > JOIN_SOURCE_MAX) err = EFBIG;
if (err != 0) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", path,
err == EFBIG ? "over 512 KiB, too long to join" : strerror(err));
return 1;
}
*len += n;
return 0;
}
// The first source, a blank line, the second.
static int build(const Join *j, size_t *len)
{
*len = 0;
if (add_source(j->first, len) != 0) return 1;
// The blank line: end the first source's last line if it has no newline.
bool ends_line = *len > 0 && built[*len - 1] == '\n';
if (!ends_line) built[(*len)++] = '\n';
built[(*len)++] = '\n';
return add_source(j->second, len);
}
int join_current(const Join *j)
{
size_t want;
if (build(j, &want) != 0) return -1;
size_t have;
int err = read_into(j->path, current, sizeof current, &have);
// A file that cannot be read is not the joined content: it gets rewritten.
return err == 0 && have == want && memcmp(current, built, want) == 0;
}
int join_write(const Join *j)
{
size_t len;
if (build(j, &len) != 0) return 1;
int err = sys_write_atomic(j->path, built, len);
if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", j->path, strerror(err));
return err == 0 ? 0 : 1;
}