/* 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 <limb/u64.h>
int
u64_pack_trim(char *dst_, size_t dlen, u64 val)
{
u8 *dst = (u8 *) dst_;
unsigned int bits = msb64(val);
unsigned int b = 0;
/* ensure little endianness */
u64p_le(&val);
for (;;) {
int n = bits > 7 ? 7 : bits;
/* enough room? */
if (b >= dlen) return -1;
/* store the 7 low bits */
dst[b] = val & 127;
/* and shift them out */
val >>= 7;
bits -= n;
if (!bits)
break;
/* add our flag: one more byte */
dst[b++] |= 128;
}
return b + 1;
}