/src/libcoap/src/coap_encode.c
Line | Count | Source |
1 | | /* coap_encode.c -- encoding and decoding of CoAP data types |
2 | | * |
3 | | * Copyright (C) 2010-2026 Olaf Bergmann <bergmann@tzi.org> |
4 | | * |
5 | | * SPDX-License-Identifier: BSD-2-Clause |
6 | | * |
7 | | * This file is part of the CoAP library libcoap. Please see |
8 | | * README for terms of use. |
9 | | */ |
10 | | |
11 | | /** |
12 | | * @file coap_encode.c |
13 | | * @brief Encoding and decoding Coap data types functions |
14 | | */ |
15 | | |
16 | | #include "coap3/coap_libcoap_build.h" |
17 | | |
18 | | /* Carsten suggested this when fls() is not available: */ |
19 | | #ifndef HAVE_FLS |
20 | | int |
21 | 378 | coap_fls(unsigned int i) { |
22 | 378 | return coap_flsll(i); |
23 | 378 | } |
24 | | #endif |
25 | | |
26 | | #ifndef HAVE_FLSLL |
27 | | int |
28 | 378 | coap_flsll(long long j) { |
29 | 378 | unsigned long long i = (unsigned long long)j; |
30 | 378 | int n; |
31 | 3.22k | for (n = 0; i; n++) |
32 | 2.85k | i >>= 1; |
33 | 378 | return n; |
34 | 378 | } |
35 | | #endif |
36 | | |
37 | | unsigned int |
38 | 0 | coap_decode_var_bytes(const uint8_t *buf, size_t len) { |
39 | 0 | unsigned int i, n = 0; |
40 | 0 | for (i = 0; i < len; ++i) |
41 | 0 | n = (n << 8) + buf[i]; |
42 | |
|
43 | 0 | return n; |
44 | 0 | } |
45 | | |
46 | | unsigned int |
47 | 0 | coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val) { |
48 | 0 | unsigned int n, i; |
49 | |
|
50 | 0 | if (val == 0) |
51 | 0 | return 0; |
52 | | |
53 | 0 | for (n = 0, i = val; i && n < sizeof(val); ++n) |
54 | 0 | i >>= 8; |
55 | |
|
56 | 0 | if (n > length) { |
57 | 0 | assert(n <= length); |
58 | 0 | return 0; |
59 | 0 | } |
60 | 0 | i = n; |
61 | 0 | while (i) { |
62 | 0 | i--; |
63 | 0 | buf[i] = val & 0xff; |
64 | 0 | val >>= 8; |
65 | 0 | } |
66 | |
|
67 | 0 | return n; |
68 | 0 | } |
69 | | |
70 | | uint64_t |
71 | 0 | coap_decode_var_bytes8(const uint8_t *buf, size_t len) { |
72 | 0 | unsigned int i; |
73 | 0 | uint64_t n = 0; |
74 | 0 | for (i = 0; i < len && i < sizeof(uint64_t); ++i) |
75 | 0 | n = (n << 8) + buf[i]; |
76 | |
|
77 | 0 | return n; |
78 | 0 | } |
79 | | |
80 | | unsigned int |
81 | 0 | coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) { |
82 | 0 | unsigned int n, i; |
83 | 0 | uint64_t tval = val; |
84 | |
|
85 | 0 | if (val == 0) |
86 | 0 | return 0; |
87 | | |
88 | 0 | for (n = 0; tval && n < sizeof(val); ++n) |
89 | 0 | tval >>= 8; |
90 | |
|
91 | 0 | if (n > length) { |
92 | 0 | assert(n <= length); |
93 | 0 | return 0; |
94 | 0 | } |
95 | 0 | i = n; |
96 | 0 | while (i) { |
97 | 0 | i--; |
98 | 0 | buf[i] = val & 0xff; |
99 | 0 | val >>= 8; |
100 | 0 | } |
101 | |
|
102 | 0 | return n; |
103 | 0 | } |