1 /* coap_encode.c -- encoding and decoding of CoAP data types 2 * 3 * Copyright (C) 2010,2011 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_internal.h" 17 18 /* Carsten suggested this when fls() is not available: */ 19 #ifndef HAVE_FLS 20 int coap_fls(unsigned int i)21 coap_fls(unsigned int i) { 22 return coap_flsll(i); 23 } 24 #endif 25 26 #ifndef HAVE_FLSLL 27 int coap_flsll(long long j)28 coap_flsll(long long j) { 29 unsigned long long i = (unsigned long long)j; 30 int n; 31 for (n = 0; i; n++) 32 i >>= 1; 33 return n; 34 } 35 #endif 36 37 unsigned int coap_decode_var_bytes(const uint8_t * buf,size_t len)38 coap_decode_var_bytes(const uint8_t *buf, size_t len) { 39 unsigned int i, n = 0; 40 for (i = 0; i < len; ++i) 41 n = (n << 8) + buf[i]; 42 43 return n; 44 } 45 46 unsigned int coap_encode_var_safe(uint8_t * buf,size_t length,unsigned int val)47 coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val) { 48 unsigned int n, i; 49 50 for (n = 0, i = val; i && n < sizeof(val); ++n) 51 i >>= 8; 52 53 if (n > length) { 54 assert(n <= length); 55 return 0; 56 } 57 i = n; 58 while (i--) { 59 buf[i] = val & 0xff; 60 val >>= 8; 61 } 62 63 return n; 64 } 65 66 uint64_t coap_decode_var_bytes8(const uint8_t * buf,size_t len)67 coap_decode_var_bytes8(const uint8_t *buf, size_t len) { 68 unsigned int i; 69 uint64_t n = 0; 70 for (i = 0; i < len && i < sizeof(uint64_t); ++i) 71 n = (n << 8) + buf[i]; 72 73 return n; 74 } 75 76 unsigned int coap_encode_var_safe8(uint8_t * buf,size_t length,uint64_t val)77 coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) { 78 unsigned int n, i; 79 uint64_t tval = val; 80 81 for (n = 0; tval && n < sizeof(val); ++n) 82 tval >>= 8; 83 84 if (n > length) { 85 assert(n <= length); 86 return 0; 87 } 88 i = n; 89 while (i--) { 90 buf[i] = val & 0xff; 91 val >>= 8; 92 } 93 94 return n; 95 } 96