Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / buffer.h / buffer_gethdr.c

/* This file is part of limb                           https://lila.oss/limb
 * Copyright (C) 2023 Olivier Brunel                          jjk@jjacky.com */
/* SPDX-License-Identifier: GPL-2.0-only */
#include <errno.h>
#include <limb/buffer.h>
#include <limb/siovec.h>
#include <limb/u32.h>
#include <limb/u64.h>

int
buffer_gethdr(buffer *b, u32 *magic, u64 *ver)
{
    int r;

    /* magic number */
    r = buffer_get(b, (char *) magic, sizeof(*magic));
    if (r <= 0) return (!r) ? (errno = EPIPE, 0) : 0;
    u32p_be(magic);

    struct iovec v[2];
    char buf[9];

    /* peek into the buffer to unpack the version number */
    do {
        buffer_rpeek(b, v);
        r = u64_unpack_trim(ver, buf, siov_gather(buf, sizeof(buf), v, 2));
    } while (r < 0 && (r = buffer_fill(b)) > 0);
    if (r <= 0) return (!r) ? (errno = EPIPE, 0) : 0;
    /* we've only peeked into the buffer, actually consume read data */
    buffer_rseek(b, r);

    return 1;
}