blob: a57d5c7095835dda32758278964739d1216617f3 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
/*
* nanowasm, a tiny WebAssembly/Wasm interpreter
* Copyright (C) 2023-2024 Xavier Del Campo Romero
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include <nanowasm/types.h>
#include <nanowasm/leb128.h>
#include <nw/io.h>
#include <nw/log.h>
#include <stdbool.h>
#include <stdint.h>
enum nw_state nwp_leb128(const struct nw_io_cfg *const cfg,
struct nw_sm_leb128 *const l, const unsigned maxbits, const bool sign)
{
uint8_t byte;
for (;;)
{
const int n = cfg->read(&byte, sizeof byte, cfg->user);
if (n < 0)
return NW_FATAL;
else if (!n)
return NW_AGAIN;
l->result |= (unsigned long long)(byte & 0x7f) << l->shift;
l->shift += 7;
if (!(byte & 0x80))
break;
else if (++l->bcnt > (maxbits + 7u - 1u) / 7u)
{
LOG("%s: overflow\n", __func__);
return NW_FATAL;
}
}
if (sign && (l->shift < maxbits) && (byte & 0x40))
l->result |= -1ll << l->shift;
return NW_OK;
}
|