Loading...
Searching...
No Matches
wire_read.h
Go to the documentation of this file.
1
16#pragma once
17#include <stdbool.h>
18#include <stdint.h>
19
20#include "io/bytes_le.h"
21
26
37static inline int32_t wire_int_or(bool is_signed, uint16_t length, const uint8_t *value, int32_t fallback)
38{
39 if (!value)
40 {
41 return fallback;
42 }
43
44 switch (length)
45 {
46 // a byte read signed is -128 to 127 and unsigned is 0 to 255
47 // that is the only thing the signedness decides at this width
48 case 1: return is_signed ? (int32_t)(int8_t)value[0] : (int32_t)value[0];
49
50 // read the pair as signed and take the sign back off when it is not wanted
51 // so the unsigned half lands on 0 to 65535 rather than going negative at the top
52 case 2: return is_signed ? (int32_t)read_i16_le(value)
53 : (int32_t)(uint16_t)read_i16_le(value);
54
55 // four bytes fill the whole width either way so the bits are the same
56 // and only the caller's reading of the top one differs
57 case 4: return read_i32_le(value);
58
59 default: return fallback;
60 }
61}
62
74static inline bool wire_cstring_terminated(const char *s, uint16_t length)
75{
76 return s && length > 0 && s[length - 1] == '\0';
77}
78
Little-endian byte readers shared by the wire-decoding stores.
static int16_t read_i16_le(const uint8_t *p)
Reads a little-endian signed 16-bit value out of a byte pair.
Definition bytes_le.h:26
static bool wire_cstring_terminated(const char *s, uint16_t length)
Whether a string of length bytes carries its terminator inside itself.
Definition wire_read.h:74
static int32_t read_i32_le(const uint8_t *p)
Reads a little-endian signed 32-bit value out of four bytes.
Definition bytes_le.h:37
static int32_t wire_int_or(bool is_signed, uint16_t length, const uint8_t *value, int32_t fallback)
Reads a little-endian integer of exactly length bytes.
Definition wire_read.h:37