Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / buffer-shldata.h / buffer_shldata_put.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-shldata.h>
#include <limb/shldata.h>

ssize_t
buffer_shldata_put(buffer *b, char *data, size_t dlen, int inplace, buffer_shldata_ctx *ctx)
{
    if (ctx->sd.len && inplace) {
        if (!shldata_encrypt(data, data, dlen, &ctx->sd))
            return (errno = EINVAL, -1);
    } else {
        if (!stralloc_readyplus(&ctx->sa, dlen)
                || !shldata_encrypt(ctx->sa.s + ctx->sa.len, data, dlen, &ctx->sd))
            return (errno = (errno == ENOMEM) ? ENOMEM : EINVAL, -1);
        /* if full data length wasn't given to init we need to store the
         * encrypted data until we're done, as the predata shall be written
         * first (with the data length) */
        if (!ctx->sd.len) {
            ctx->sa.len += dlen;
            return 0;
        }
    }

    return buffer_put(b, (inplace) ? data : ctx->sa.s, dlen);
}